如何在java中的静态方法中获取调用方类的实例?
例如:如何在java中的静态方法中获取调用方类的实例?,java,inheritance,static,Java,Inheritance,Static,例如: public class MyParentClass { static MyParentClass AStaticMethod() { //get a new childclass instace here //modify this instance return(ChildClassInstance); } } public class AChildClass extends ParentClass {} 当从AsticMethod调用时,As
public class MyParentClass
{
static MyParentClass AStaticMethod()
{
//get a new childclass instace here
//modify this instance
return(ChildClassInstance);
}
}
public class AChildClass extends ParentClass {}
当从AsticMethod
调用时,AsticMethod
是否可以获得AChildClass
的新安装(AChildClass.AsticMethod
)
我见过类似的代码使用技巧,比如使用堆栈跟踪或抛出异常并捕获它,但我正在寻找一种更干净的方法来实现这一点
将AStaticMethod
视为子类的通用初始值设定项
我记得我在PHP中做过类似的事情,但它严重依赖于动态弱类型和语言的反射
我正在寻找一种更干净的方法
这个
没有任何干净的方法可以做到这一点
您应该进行一些重构,比如将初始值设定项和使用类(比如AChildClass
)划分为不同的类。我想您可以采取一种方法,将所有对象包装在动态代理中,或者使用AoP
钩住执行路径。无论何时调用一个方法,您都可以将此信息存储在某个静态调用日志类中。然而,我看不出有什么干净的方法可以达到你的要求
您不需要显式地抛出并捕获异常,只需使用
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
}
注意:getStackTrace
的实际内容不能保证,例如,它们可能会释放元素。因此,只在调试时使用它,而不是在生产中使用。我可以,但是我必须在每个子类中添加我的大初始值设定项方法,只更改类名,并在每次需要更改方法时重复该过程。一个真正的维护噩梦。@user644718您可以使用继承来处理它。真正的再造解决方案取决于您的程序。