我想知道如何选择,操纵创建对象的类.
代码:
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)
基本上你不能.如果您的其他类需要知道实例或创建它的类,您应该通过构造函数传递该信息.例如:
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
参数.
归档时间: |
|
查看次数: |
142 次 |
最近记录: |