Java中的扩展私有字段

huangapple go评论73阅读模式
英文:

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;    &lt;-- 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);
    }
}

huangapple
  • 本文由 发表于 2020年7月25日 15:21:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63085552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定