object is not an instance of declaring class


错误信息:object is not an instance of declaring class

说明Class没有实例化;
解决办法:
由于没有实力化可以有如下两种方法:
1、反射方法定义成为static的,故被反射类就不需要实例化;
2、method.invoke(class.newInstance(), args);

 

举栗子:对应第一种方法

public static void testSys(String msgs) {
System.out.println("java 反射机制调用方法执行,msg:" + msgs);
}

@Test
public void test(){
System.out.println("-------------获取当前类-----------------------");
String msg = "hello";
Class<? extends Test> aClass1 = getClass();
Method[] methods = aClass1.getMethods();
for (Method method : methods) {
if (method.getName().equals("testSys")) {
System.out.println("匹配成功,开始执行反射方法,methodName:" + method.getName());
System.out.println("aClass1:" + aClass1);
System.out.println("aClass1Name:" + aClass1.getName());
method.invoke(aClass1, msg);
System.out.println("执行完成.....");
}
}
}

举栗子:对应第二种方法

public void testSys(String msgs) {
System.out.println("java 反射机制调用方法执行,msg:" + msgs);
}

@Test
public void test(){
System.out.println("-------------获取当前类-----------------------");
String msg = "hello";
Class<? extends Test> aClass1 = getClass();
Method[] methods = aClass1.getMethods();
for (Method method : methods) {
if (method.getName().equals("testSys")) {
System.out.println("匹配成功,开始执行反射方法,methodName:" + method.getName());
System.out.println("aClass1:" + aClass1);
System.out.println("aClass1Name:" + aClass1.getName());
method.invoke(aClass1.newInstance(), msg);
System.out.println("执行完成.....");
}
}
}
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 object is not an instance of declaring class 报错:java.lang.IllegalArgumentException: object is not an instance of declaring class java.lang.IllegalArgumentException: object is not an instance of declaring class 项目报错小记——项目报异常java.lang.IllegalArgumentException: object is not an instance of declaring class及不执行shiro的doGetAuthorizationInfo方法 C++之类(Class),对象(Object)以及实例(Instance)的关系 13_Python的面向对象编程-类class,对象object,实例instance Class与Class有何区别呢 unity NullReferenceException: Object reference not set to an instance of an object 对类和实例的理解.(class、instance) Java class,Object,Class的区别
 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM