使用反射检索对象的类名

时间:2014-08-23 17:46:36

标签: 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() {
        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());
        // }

    }

}

我不明白为什么在编译上面的代码时会出现以下错误。

TryReflection.java:31: error: cannot find symbol
    Method[] methods = myObject.class.getMethods();
                       ^
  symbol:   class myObject
  location: class TryReflection
1 error

2 个答案:

答案 0 :(得分:1)

myObject是类的实例,因此您应该使用myObject.getClass()。或者,只需致电TryReflection.class

答案 1 :(得分:1)

由于您的对象实例可用,因此您需要使用myObject.getClass()

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

请参阅official tutorials了解详情。

相关问题