java – 如何在不使用setter的情况下将值设置为类变量

前端之家收集整理的这篇文章主要介绍了java – 如何在不使用setter的情况下将值设置为类变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在不使用setter的情况下向Object变量插入值.怎么可能.

这是一个例子

  1. Class X{
  2. String variableName;
  3. // getters and setters
  4. }

现在我有一个函数,它包含变量名,要设置的值和Class X的Object.

我试图使用泛型方法将值设置为Object(objectOfClass),并在相应的变量(variableName)中传递值i(valueToBeSet).

  1. Object functionName(String variableName,Object valueToBeSet,Object objectOfClass){
  2.  
  3. //I want to do the exact same thing as it does when setting the value using the below statement
  4. //objectOfClass.setX(valueToBeSet);
  5.  
  6. return objectOfClass;
  7. }

解决方法

代码未经过测试.你可以试试这个.

要导入的类

  1. import java.beans.BeanInfo;
  2. import java.beans.IntrospectionException;
  3. import java.beans.Introspector;
  4. import java.beans.PropertyDescriptor;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.lang.reflect.Method;

方法

  1. public Object functionName(String variableName,Object objectOfClass) throws IntrospectionException,NoSuchMethodException,SecurityException,IllegalAccessException,IllegalArgumentException,InvocationTargetException{
  2.  
  3. //I want to do the exact same thing as it does when setting the value using the below statement
  4. //objectOfClass.setX(valueToBeSet);
  5. Class clazz = objectOfClass.getClass();
  6. BeanInfo beanInfo = Introspector.getBeanInfo(clazz,Object.class); // get bean info
  7. PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); // gets all info about all properties of the class.
  8. for (PropertyDescriptor descriptor : props) {
  9. String property = descriptor.getDisplayName();
  10. if(property.equals(variableName)) {
  11. String setter = descriptor.getWriteMethod().getName();
  12. Class parameterType = descriptor.getPropertyType();
  13. Method setterMethod = clazz.getDeclaredMethod(setter,parameterType); //Using Method Reflection
  14. setterMethod.invoke(objectOfClass,valueToBeSet);
  15. }
  16.  
  17. }
  18.  
  19. return objectOfClass;
  20. }

猜你在找的Java相关文章