Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检索对象';使用反射的类名称_Java_Class_Object_Reflection_Import - Fatal编程技术网

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());
}