java反射小例子

来源:互联网 发布:2017网络效应的答案 编辑:程序博客网 时间:2024/05/03 11:05
 

package com.csdn.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Test {
 private int id;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }
 public static void setValueByField(String field,Object o,Object value) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
 {
  Class c = o.getClass();
  Field[] fields =c.getDeclaredFields();
  for(Field ff :fields)
  {
   if(ff.getName().equals(field))
   {
    String medthodName = "set"+field.substring(0,1).toUpperCase()+field.substring(1);
    c.getDeclaredMethod(medthodName, ff.getType()).invoke(o, value);
   }
  }
 }

 public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
  Test t = new Test();
  System.out.println(t.getId());
  setValueByField("id",t,new Integer(10));
  System.out.println(t.getId());
 }
}

原创粉丝点击