在 Java 中,“私有化 Field 字段”通常指将类的字段设置为 private,并通过受控方式访问,以实现封装(Encapsulation)。下面从基础做法、进阶技巧、框架/反射场景三个层面说明。
private 修饰字段(标准封装)public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负");
}
this.age = age;
}
}
✅ 特点
public class Config {
private final String appName;
public Config(String appName) {
this.appName = appName;
}
public String getAppName() {
return appName;
}
}
✅ 外部完全无法修改
public record Point(int x, int y) {}
private finalprivate 并不能阻止反射:
Field f = user.getClass().getDeclaredField("name");
f.setAccessible(true);
f.set(user, "hack");
record(最安全)public record Safe(String value) {}
public class Secret {
private final String token;
private Secret(String token) {
this.token = token;
}
public static Secret of(String token) {
return new Secret(token);
}
public String getToken() {
return token;
}
}
module com.example {
exports com.example.api;
}
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
✅ 字段只服务于类本身逻辑
| 需求 | 推荐方式 |
|---|---|
| 基本封装 | private + getter/setter |
| 只读 | private final |
| 不可变 | record |
| 防反射 | record / 模块系统 |
| 内部状态 | private 方法内使用 |
如果你指的是 “不暴露 Field 给框架(如 Jackson / Spring)” 或 “如何彻底隐藏字段”,可以告诉我具体使用场景,我可以针对性讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。