英文:
Extension private field in java
问题
我阅读了Spring Data源代码并遇到了一个问题:
JdbcTemplate有一个方法:
public void setDataSource(@Nullable DataSource dataSource) {
this.dataSource = dataSource;
}
我发现这个this.dataSource是从它的父类JdbcAccessor继承而来的,定义如下:
private DataSource dataSource;
我的问题是:为什么扩展类JdbcTemplate能访问它父类的私有字段?
我尝试像下面这样使用,但是IDE显示有错误:
public abstract class A {
@Nullable
private Integer a;
}
public class B extends A {
public void setA(@Nullable Integer a) {
this.a = a; // <-- 错误
}
}
英文:
I read the Spring Data source and meet a question:
JdbcTemplate has a method:
public void setDataSource(@Nullable DataSource dataSource) {
this.dataSource = dataSource;
}
and I find that this.dataSource is from it`s father class JdbcAccessor.declearing as follow
private DataSource dataSource;
my question is: why extension class JdbcTemplate can access its father class`s private field?
I try to use it as follow and find IDE show its wrong
public abstract class A {
@Nullable
private Integer a;
}
public class B extends A {
public void setA(@Nullable Integer a) {
this.a = a; <-- Wrong
}
}
答案1
得分: 2
不能。很可能您使用了某种无法正确反编译的反编译器。实际的代码在JDBCTemplate中如下所示:
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
而setDataSource
方法位于JDBCAccessor中。
英文:
It can not. Most likely you used some sort of decompiler which couldn't properly decompile it. The actual code is like this in JDBCTemplate
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
And setDatasource method is in JDBCAccessor.
答案2
得分: 0
你无法在另一个类中访问私有属性。因此,您需要添加一个setter方法来向私有属性添加值。
public abstract class A {
@Nullable
private Integer a;
public void setValue(Integer a){
this.a = a;
}
}
public class B extends A {
public void setA(@Nullable Integer a) {
this.setValue(a);
}
}
英文:
You cannot access private properties in another class. So you need to add a setter method to add values to private properties.
public abstract class A {
@Nullable
private Integer a;
public void setValue(Integer a){
this.a=a;
}
}
public class B extends A {
public void setA(@Nullable Integer a) {
this.setValue(a);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论