在抽象 class 的方法中,我如何知道我正在使用哪个实例?
How can I know which instance i am working with, inside a method of an abstract class?
我有一个抽象 class,我想知道是否有可能在其中一个方法中知道 class 的实例。
我的意思是有没有办法得到它。像一些 java 方法,比如 myClass.whereAmI()
或类似的东西。
例如:
public abstract class MyClass {
public void myMethod(String string){
String instance = MyClass.getClass(); //I want to get the type of the instance.
....
}
}
这可能吗?
只需使用继承自java.lang.Object
的getClass()
实例方法:
public void myMethod(String string) {
Class<?> instanceClass = getClass();
String instanceClassName = instanceClass.getName();
}
我有一个抽象 class,我想知道是否有可能在其中一个方法中知道 class 的实例。
我的意思是有没有办法得到它。像一些 java 方法,比如 myClass.whereAmI()
或类似的东西。
例如:
public abstract class MyClass {
public void myMethod(String string){
String instance = MyClass.getClass(); //I want to get the type of the instance.
....
}
}
这可能吗?
只需使用继承自java.lang.Object
的getClass()
实例方法:
public void myMethod(String string) {
Class<?> instanceClass = getClass();
String instanceClassName = instanceClass.getName();
}