【问题标题】:Invoke getter in java with reflections用反射在java中调用getter
【发布时间】:2014-05-23 06:33:55
【问题描述】:

我想用反射调用 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.

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

【问题讨论】:

  • this 和实例是什么? m 叫什么名字?
  • 你没有先创建实例...
  • 我搜了一下,发现了一个了不起的similar question
  • 这是我自己的班级,在本例中为Block。我有很多要使用此代码的类。我在 Block 类中直接尝试过。如果它可以工作,我想把它放在超类中,所以我只需要编写这个方法一次。在m 中有所有的getter 方法。我首先创建了实例。

标签: java reflection getter


【解决方案1】:
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();
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多