从封闭类访问实例属性

时间:2017-06-23 10:26:51

标签: java

我是java的新手,在这个例子中是否可以从ClassB获取ClassA的id?

public class ClassA {

    private Long id;

    private List<ClassB> listOfClassB;

[...]
}

public class ClassB {

    private Long num;

    public boolean isValidRow() {
        return this.num > ***ClassA.this.getId()***;
    }

[...]
}

4 个答案:

答案 0 :(得分:0)

要获取id的{​​{1}}字段,您需要在ClassA中拥有ClassA的实例,例如:

ClassB

以这种方式启动它:

public class ClassA {

    private Long id;

    private List<ClassB> listOfClassB;

[...]
}

public class ClassB {

    private Long num;
    private ClassA a;

    public ClassB(Long num, ClassA a) {
        this.num = num;
        this.a = a;
    }

    public boolean isValidRow() {
        return this.num > a.getId();
    }

[...]
}

答案 1 :(得分:0)

尝试以下方法:

public class ClassB {

    private ClassA a;
    private Long num;

    public ClassB(ClassA a){
        this.a=a;
    }

    public boolean isValidRow() {
        return this.num > a.getId();
    }
}

按如下方式使用:

...
ClassA a = new ClassA();
ClassB b = new ClassB(a);
...

或者如果你在A:

中创建Bs
ClassB b = new ClassB(this);

答案 2 :(得分:0)

这仅适用于嵌套类:

class ClassA {
    private long id;

    class ClassB {
        ClassA.this.getId(); // Will work here
    }
}

要使它在您的情况下工作,您需要将ClassA的实例注入ClassB的实例:

class ClassA {
    long id;
}

class ClassB {
    private ClassA a;
    ClassB(ClassA a) {
        this.a = a;
    }

    void someMethod() {
        long id = a.getId();
    }
}

答案 3 :(得分:0)

您无法获得ClassA的ID,但您可以从ClassA

实例获取

例如:

    ClassA a =new ClassA():
    ClassB b =new ClassB(a);

ClassA的:

public class ClassA{
   private Integer id;
   public Integer getId(){return id;}
}        

ClassB的:

    public class B {
     //whatever
     private A a;
     public B(A a){
        this.a=a;
     }

    public void someMethod(){
      //whatever
      t.getId() // here you have the id.
     }
}

现在,您ClassB的任何地方都可以访问a.getId()