gpt4 book ai didi

java - 使用反射在 Java 中调用 getter

转载 作者:行者123 更新时间:2023-11-29 08:50:26 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于java - 使用反射在 Java 中调用 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22973025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com