我是靠谱客的博主 无聊苗条,这篇文章主要介绍java.lang.IllegalArgumentException: object is not an instance of declaring class,现在分享给大家,希望可以做个参考。
java.lang.IllegalArgumentException: object is not an instance of declaring class
现象:今天在使用反射的时候报错object is not an instance of declaring class
原因:其实是自己一时粗心,在调用方法的时候,传参数错误导致这个错误。废话不多说,直接看代码。
- 简单的实体类Person
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getString() { return "Hello World !!!"; } }
- 简单使用main方法调用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31public class TestPerson { public static void main(String[] args) throws Exception { // 反射:在运行的时候,对于任意一个类,我们可以获取这个类的所 //有属性和方法;对于任意一个对象,都可以调用这个对象的任意一个方法和属性。 //1. class.forname Class<?> aClass = Class.forName("com.ma.relfect.Person"); //2. 获取变量 Field[] declaredFields = aClass.getDeclaredFields(); for (Field field : declaredFields) { System.out.println(field); } System.out.println("==="); // 3. 获取方法 Method[] declaredMethods = aClass.getMethods(); for (Method method : declaredMethods) { System.out.println(method); } Method method = aClass.getDeclaredMethod("getString"); // 通过反射调用类的方法 Object obj = aClass.newInstance(); //在调用method.invoke 的时候,第一个参数传递的应该是调用 调用该方法的本身的对象,而我粗心的传递成了Class对象,所以出现问题。 // 也就是说这里本应该传这个对象的实例,(毕竟是对象调用方法),我错误的传递成了Class对象。 // 错误:String invoke = (String)methd.invoke(aClass); // 正确: String invoke = (String)method.invoke(obj); System.out.println(invoke); } }
- 修改后,再次运行。
okay。
最后
以上就是无聊苗条最近收集整理的关于java.lang.IllegalArgumentException: object is not an instance of declaring class的全部内容,更多相关java.lang.IllegalArgumentException:内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复