Java中的扩展私有字段

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

Extension private field in java

问题

我阅读了Spring Data源代码并遇到了一个问题:
JdbcTemplate有一个方法:

  1. public void setDataSource(@Nullable DataSource dataSource) {
  2. this.dataSource = dataSource;
  3. }

我发现这个this.dataSource是从它的父类JdbcAccessor继承而来的,定义如下:

  1. private DataSource dataSource;

我的问题是:为什么扩展类JdbcTemplate能访问它父类的私有字段?
我尝试像下面这样使用,但是IDE显示有错误:

  1. public abstract class A {
  2. @Nullable
  3. private Integer a;
  4. }
  5. public class B extends A {
  6. public void setA(@Nullable Integer a) {
  7. this.a = a; // <-- 错误
  8. }
  9. }
英文:

I read the Spring Data source and meet a question:
JdbcTemplate has a method:

  1. public void setDataSource(@Nullable DataSource dataSource) {
  2. this.dataSource = dataSource;
  3. }

and I find that this.dataSource is from it`s father class JdbcAccessor.declearing as follow

  1. 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

  1. public abstract class A {
  2. @Nullable
  3. private Integer a;
  4. }
  5. public class B extends A {
  6. public void setA(@Nullable Integer a) {
  7. this.a = a; &lt;-- Wrong
  8. }
  9. }

答案1

得分: 2

不能。很可能您使用了某种无法正确反编译的反编译器。实际的代码在JDBCTemplate中如下所示:

  1. public JdbcTemplate(DataSource dataSource) {
  2. setDataSource(dataSource);
  3. afterPropertiesSet();
  4. }

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

  1. public JdbcTemplate(DataSource dataSource) {
  2. setDataSource(dataSource);
  3. afterPropertiesSet();
  4. }

And setDatasource method is in JDBCAccessor.

答案2

得分: 0

你无法在另一个类中访问私有属性。因此,您需要添加一个setter方法来向私有属性添加值。

  1. public abstract class A {
  2. @Nullable
  3. private Integer a;
  4. public void setValue(Integer a){
  5. this.a = a;
  6. }
  7. }
  8. public class B extends A {
  9. public void setA(@Nullable Integer a) {
  10. this.setValue(a);
  11. }
  12. }
英文:

You cannot access private properties in another class. So you need to add a setter method to add values to private properties.

  1. public abstract class A {
  2. @Nullable
  3. private Integer a;
  4. public void setValue(Integer a){
  5. this.a=a;
  6. }
  7. }
  8. public class B extends A {
  9. public void setA(@Nullable Integer a) {
  10. this.setValue(a);
  11. }
  12. }

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:

确定