Java 检索对象';使用反射的类名称
我不明白为什么在编译上述代码时会出现以下错误Java 检索对象';使用反射的类名称,java,class,object,reflection,import,Java,Class,Object,Reflection,Import,我不明白为什么在编译上述代码时会出现以下错误 import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Member; import static java.lang.System.out; public class TryReflection { public TryReflection
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Member;
import static java.lang.System.out;
public class TryReflection {
public TryReflection() {
int a = 0;
}
public static int getMax() {
int max = 0;
return max;
}
public static void main(String[] args) {
TryReflection myObject = new TryReflection();
int ret = myObject.getMax();
System.out.printf("max is %d\n", ret);
Method[] methods = myObject.class.getMethods();
// for(Method method:methods) {
// System.out.println("method = " + method.getName());
// }
}
}
myObject
是类的实例,因此应该使用myObject.getClass()
。或者,只需调用TryReflection.class
,因为您有一个对象的实例可用,所以需要使用myObject.getClass()
有关详细信息,请参阅。您需要使用
getClass()
。
TryReflection.java:31: error: cannot find symbol
Method[] methods = myObject.class.getMethods();
^
symbol: class myObject
location: class TryReflection
1 error
TryReflection myObject = new TryReflection();
int ret = myObject.getMax();
System.out.printf("max is %d\n", ret);
Method[] methods = myObject.getClass().getMethods();
for (Method method : methods) {
System.out.println("method = " + method.getName());
}