Java 如何在while循环中进行反射而不进行初始化
此代码位于while循环中。当我将Method设置为null时,我得到一个null点异常。如何使代码在while循环中运行 首先,永远不要默默地忽略异常。在这种情况下,如果捕获并忽略第一个异常,则Java 如何在while循环中进行反射而不进行初始化,java,reflection,methods,initialization,invoke,Java,Reflection,Methods,Initialization,Invoke,此代码位于while循环中。当我将Method设置为null时,我得到一个null点异常。如何使代码在while循环中运行 首先,永远不要默默地忽略异常。在这种情况下,如果捕获并忽略第一个异常,则方法将为空如果第一个try{}块中存在异常,则变量方法不会初始化。这就是为什么会出现编译错误 试试这个: Method method; try { method = m.getClass().getMethod(h); }
方法
将为空
如果第一个try{}
块中存在异常,则变量方法
不会初始化。这就是为什么会出现编译错误
试试这个:
Method method;
try {
method = m.getClass().getMethod(h);
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
}
try {
//line below wants me to initialize it
method.invoke(m);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
public
class ReflectiveCall
{
public static
void main(String args[])
{
ReflectiveCall m = new ReflectiveCall();
String h = "foo";
while (true)
{
Method method;
try
{
method = m.getClass().getMethod(h);
method.invoke(m);
}
catch (SecurityException e)
{
}
catch (NoSuchMethodException e)
{
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
catch (InvocationTargetException e)
{
}
}
}
public
void foo()
{
System.out.println("foo");
}
}