例如:
public class MyParentClass
{
static MyParentClass AStaticMethod()
{
//get a new childclass instace here
//modify this instance
return(ChildClassInstance);
}
}
public class AChildClass extends ParentClass {}
AStaticMethod
从AChildClass
调用AChildClass.AStaticMethod
时是否可以获得AStaticMethod
的新实例?
我见过类似的代码,比如使用堆栈跟踪或抛出异常并捕获它,但我正在寻找一种更简洁的方法来实现这一点。
将{{1}}视为子类的通用初始值设定项。
我记得我在PHP中做过类似的事情,但它很大程度上依赖于语言的动态弱类型和反映。
答案 0 :(得分:2)
我正在寻找一种更清洁的方法 此
没有任何干净的方法可以做到这一点。
你应该做一些重构,比如将初始值设定项和用法类(如AChildClass
)分成不同的类。
答案 1 :(得分:0)
我认为你可以采用一种方法,你可以将所有对象包装在dynamic proxy
中,或者使用AoP
挂钩到执行路径中。每当调用一个方法时,您都可以将此信息存储在某个静态invocationLogging类中。但是,我看不到 clean 实现你所要求的方式。
您没有明确需要抛出并捕获异常,您可以使用
来获取它 StackTraceElement[] trace = Thread.currentThread().getStackTrace();
其中数组中的第一个元素应与最后一个调用的方法相对应。例如,
public static void main(String[] args) {
first();
}
public static void first() {
second();
}
public static void second() {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
System.out.println(trace[0].getMethodName()); // getStackTrace
System.out.println(trace[1].getMethodName()); // second
System.out.println(trace[2].getMethodName()); // first
System.out.println(trace[3].getMethodName()); // main
}