问题描述
在学习反射过程中遇到java.lang.IllegalArgumentException: object is not an instance of declaring class 异常
测试代码
@Test
public void testGetMethod() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// 1.获取字节码对象
Class Ccat = Cat.class;
// 创建
Constructor declaredConstructor = Ccat.getDeclaredConstructor();
Cat cat = (Cat) declaredConstructor.newInstance();
// 2.获取成员方法
Method Meat = Ccat.getDeclaredMethod("eat");
System.out.println(Meat.getName()+
"-->"+Meat.getParameterCount()+
"-->"+Meat.getReturnType());
// 3.方法调用eat无参
System.out.println(Meat.invoke(cat));
// 调用eat带参返回值
Method eat = Ccat.getDeclaredMethod("eat", String.class);
eat.setAccessible(true);
System.out.println(eat.invoke("fish"));
}
猫类代码
package com.itheima.d2_reflect;
public class Cat {
public static int a;
public static final String COUNTRY = "中国";
private String name;
private int age;
public Cat(){
System.out.println("无参数构造器执行了~~");
}
private Cat(String name, int age) {
System.out.println("有参数构造器执行了~~");
this.name = name;
this.age = age;
}
private void run(){
System.out.println("🐱跑的贼快~~");
}
public void eat(){
System.out.println("🐱爱吃猫粮~");
}
private String eat(String name){
return "🐱最爱吃:" + name;
}
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;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
解决方案
测试类代码修改后
@Test
public void testGetMethod() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// 1.获取字节码对象
Class Ccat = Cat.class;
// 创建
Constructor declaredConstructor = Ccat.getDeclaredConstructor();
Cat cat = (Cat) declaredConstructor.newInstance();
// 2.获取成员方法
Method Meat = Ccat.getDeclaredMethod("eat");
System.out.println(Meat.getName()+
"-->"+Meat.getParameterCount()+
"-->"+Meat.getReturnType());
// 3.方法调用eat无参
System.out.println(Meat.invoke(cat));
// 调用eat带参返回值
Method eat = Ccat.getDeclaredMethod("eat", String.class);
eat.setAccessible(true);
System.out.println(eat.invoke("fish"));
}