用反射在java中调用getter

时间:2014-04-09 20:12:20

标签: java reflection getter

我想用反射调用吸气剂。我这样累了:

for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors()){

    Method m = propertyDescriptor.getReadMethod();

    if(m != null)
        System.out.println(m.invoke(this).toString());
}

我总是在调用方法的行中得到NullPointerException。

异常的堆栈跟踪:

org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.

我搜索了这个问题,但我没有得到解决方案。

1 个答案:

答案 0 :(得分:0)

public static void main(String... args) {
if (args.length != 4) {
    err.format("Usage: java Deet <classname> <langauge> <country> <variant>%n");
    return;
}

try {
    Class<?> c = Class.forName(args[0]);
    Object t = c.newInstance();

    Method[] allMethods = c.getDeclaredMethods();
    for (Method m : allMethods) {
    String mname = m.getName();
    if (!mname.startsWith("test")
        || (m.getGenericReturnType() != boolean.class)) {
        continue;
    }
    Type[] pType = m.getGenericParameterTypes();
    if ((pType.length != 1)
        || Locale.class.isAssignableFrom(pType[0].getClass())) {
        continue;
    }

    out.format("invoking %s()%n", mname);
    try {
        m.setAccessible(true);
        Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
        out.format("%s() returned %b%n", mname, (Boolean) o);

    // Handle any exceptions thrown by method to be invoked.
    } catch (InvocationTargetException x) {
        Throwable cause = x.getCause();
        err.format("invocation of %s failed: %s%n",
               mname, cause.getMessage());
    }
    }

    // production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
    x.printStackTrace();
} catch (InstantiationException x) {
    x.printStackTrace();
} catch (IllegalAccessException x) {
    x.printStackTrace();
}
}