java.lang.IllegalArgumentException: object is not an instance of declaring class(反射中使用)

本文通过一个具体的代码案例,分析了使用Java反射机制时出现的异常原因,并给出了正确的实现方式。强调了在构建Method对象及调用时,保持类对象一致性的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在编写代码途中为了省事利用反射来进行代码属性的赋值,然后抛了一个奇怪的异常,废话不多说直接上代码

	

Class<CompGoods> clazz = CompGoods.class;
//为购物车的选配信息赋值
		Class<CompGoodsParts> cla=CompGoodsParts.class;
		for(int k=1;k<=9;k++) {
			Method declaredMethod = cla.getDeclaredMethod("getPart"+k);
			if(declaredMethod.invoke(queryParts)!=null) {
				Method newMethod = cla.getDeclaredMethod("setPart"+k,String.class);
				newMethod.invoke(compGoods,declaredMethod.invoke(queryParts));
			}
		}
		

在调用第二个newMethod方法时抛异常,仔细检查发现是我想构建这个Method方法应该是CompGoods对象里的方法,然而我却用了CompGoodsParts对象去构建,并且我调用这个方法时用的是CompGoods这个对象去掉用

解决办法:用class对象去构建的method,和调用method的对象必须是同一个

    

Method declaredMethod2 = clazz.getDeclaredMethod("set" +fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1),fields[i].getType());		
					if (declaredMethod.invoke(goodsCmpId)!=null) {	
//调用此method对象必须和构建出这个method对象一致						
declaredMethod2.invoke(compGoods, declaredMethod.invoke(goodsCmpId));
					}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值