大佬教程收集整理的这篇文章主要介绍了如何在不使用设置器的情况下为类变量设置值,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
此代码未经测试。你可以试试看
import java.beans.beanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public Object functionname(String variablename, Object valuetoBeSet, Object objectOfClass) throws IntrospectionException, NoSuchMethodException, SecurityException, illegalaccessexception, IllegalArgumentexception, InvocationTargetException{
//I want to do the exact same thing as it does when setTing the value using the below statement
//objectOfClass.setX(valuetoBeSet);
Class clazz = objectOfClass.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class); // get bean info
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); // gets all info about all propertIEs of the class.
for (PropertyDescriptor descriptor : props) {
String property = descriptor.getdisplayname();
if(property.equals(variableName)) {
String setter = descriptor.getWriteMethod().getname();
Class parameterType = descriptor.getPropertyType();
Method setterMethod = clazz.getDeclaredMethod(setter, parameterTypE); //Using Method Reflection
setterMethod.invoke(objectOfClass, valuetoBeSet);
}
}
return objectOfClass;
}
我想在Object
不使用设置器的情况下将值插入变量。如果有可能怎么办。
这是一个例子
Class X{
String variablename;
// getters and setters
}
现在我有一个包含variable name
,value to be set
和的函数Object of the Class X
。
我试图使用一种通用方法将值设置为Object(objectOfClass),而值我已经valueToBeSet
在相应的variable(variablename
)中通过了()。
Object functionName(String variablename,Object valueToBeSet,Object objectOfClass){
//I want to do the exact same thing as it does when setTing the value using the below statement
//objectOfClass.setX(valueToBeSet);
return objectOfClass;
}
以上是大佬教程为你收集整理的如何在不使用设置器的情况下为类变量设置值全部内容,希望文章能够帮你解决如何在不使用设置器的情况下为类变量设置值所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。