碰到一个异常,先看代码:
本意是利用反射获得一个类中的所有方法,然后执行此方法。
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, InterruptedException {
Class<?> c = Class.forName("com.day14.Test02Class");
Test02Class o =(Test02Class)c.getConstructor().newInstance();
Method[] methods = c.getMethods();
for (Method method : methods) {
method.invoke(o);
}
}
public class Test02Class {
public void test01() {
System.out.println("test01");
}
public void test02() {
System.out.println("test02");
}
public void test03() {
System.out.println("test03");
}
public void test04() {
System.out.println("test04");
}
}
奈何报了异常:(神坑啊!我的天,颠覆人生观啊!)
test01
test02
test03
test04
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com,day14.Test02.main(Test02.java:17)
Caused by: java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
... 5 more
使劲往跟的异常找,奈何水平有限找不到原因:
其它帖子说这个是线程没拥有锁对象时,调用了wait()、notify().等方法,所致。
但是脑回路来了,我就换了个循环:
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, InterruptedException {
Class<?> c = Class.forName("com.day14.Test02Class");
Test02Class o =(Test02Class)c.getConstructor().newInstance();
Method[] methods = c.getMethods();
//不使用foreach循环就没有问题,这是为啥呢?
for (int i = 0; i < 4; i++) {
methods[i].invoke(o);
}
}
解决办法:
根据其它帖子的知识我决定采用synchronized()同步代码块,锁对象是o,奈何这样也不正确。结果是:错误不报了。但是线程卡住了。
如果你也遇到这样的异常,还请大佬赐教!
然鹅,更奇怪的事情发生了,我就cao了!
这样的代码竟然不能执行:
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, InterruptedException {
Class<?> c = Class.forName("com.day14.Test02Class");
Test02Class o =(Test02Class)c.getConstructor().newInstance();
Method[] methods = c.getMethods();
Arrays.sort(methods,(m1,m2)->m1.getName().compareTo(m2.getName()));
//
for (int i = 0; i < 4; i++) {
if (methods[i].isAnnotationPresent(MyTest02.class)) {
methods[i].invoke(o);
}
}
}
最后终于发现,我真蠢!
Method[] methods = c.getMethods(); 获取的是类中的所有方法,这里包括继承自Object,的方法,所以才有了执行wait()方法的异常。