Java Call类创建了一个对象

LeS*_*Sam 3 java

我想知道如何选择,操纵创建对象的类.

代码:

public myclass(){

       public anotherclass a = new anotherclass();    

}
Run Code Online (Sandbox Code Playgroud)

另一类:

      //how to use the class that created this class ?
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

基本上你不能.如果您的其他类需要知道实例或创建它的类,您应该通过构造函数传递该信息.例如:

public class Parent {
    private final Child child;

    public Parent() {
        child = new Child(this);
    }
}

public class Child {
    private final Parent parent;

    public Child(Parent parent) {
        this.parent = parent;
    }
}
Run Code Online (Sandbox Code Playgroud)

(这使得子实例可以使用父实例 - 如果您只对该感兴趣,那么您将通过Parent.class并且Child构造函数将使用Class<?> parentClass参数.