object is not an instance of declaring class 反射异常

本文探讨了在Java中使用反射执行非静态方法时出现的objectisnotaninstanceofdeclaringclass异常原因及解决方案。提供了两种解决方法:一是将方法声明为静态;二是确保在调用前正确实例化对象。

在使用反射执行一个方法时常遇到object is not an instance of declaring class的异常,如下代码:import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import cn.rdt.famework.frame.config.FrameConstant; public class PrimaryKeyUtils { // public synchronized String getPrimaryKey() { String pk = ""; StringBuffer primaryKey = new StringBuffer(new SimpleDateFormat( "yyMMddHHmmssSSS").format(new Date())); int tpk = FrameConstant.PRIMARY_KEY; if (tpk < 9999) { tpk++; } else { tpk = 1000; } FrameConstant.PRIMARY_KEY = tpk; pk = primaryKey.append(String.valueOf(tpk)).toString(); primaryKey = null; return pk; } public String GetPrimaryKey(String mothed){ String primaryKey = ""; try { Class c = PrimaryKeyUtils.class; Method m = c.getMethod(mothed,new Class[]{}); // Object obj=c.newInstance(); m.invoke(mothed,null); primaryKey = String.valueOf(m.invoke(c.newInstance() ,new Object[]{})); } catch (Exception e) { e.printStackTrace(); } return primaryKey; } public static void main(String[] args) { PrimaryKeyUtils primaryKey = new PrimaryKeyUtils(); System.out.println(primaryKey.GetPrimaryKey("getPrimaryKey")); } }

第34行会报object is not an instance of declaring class错 对象不是声明类的一个实例。解决办法如下:

第一种:反射执行的方法 getPrimaryKey() 改成静态的

第二种:在执行方法前先实例化类。m.invoke(mothed,null)改为m.invoke(c.newInstance(),null)或者m.invoke(new PrimaryKeyUtils(),null)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值