//为name字段设置值
Field field = clazz.getDeclaredField("name"); field.setAccessible(true); //避免private不可访问抛出异常field.set(sb, "royzhou1985"); System.out.println("modify name using Field:=" + sb.getName() + "\n");
//列出类SimpleBean的所有方法
Method[] methods = clazz.getDeclaredMethods(); System.out.println("get methods of class SimpleBean:");
for(Method method : methods) {
if("setHobby".equals(method.getName())) {
//动态调用类的方法来为hobby设置值
method.invoke(sb, new Object[]{new String[]{"tennis","fishing"}});
}
System.out.println(method.getName());
}
System.out.println("\nset by invoke Method"); System.out.println(sb);
}
}
package com.royzhou.bean;
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = SimpleBean.class;
//使用无参构造函数实例化bean
SimpleBean sb = (SimpleBean)clazz.newInstance(); System.out.println(sb);
//使用有参构造函数实例化bean
Constructor constructor = clazz.getConstructor(new Class[]{String.class, String[].class}); sb = (SimpleBean)constructor.newInstance(new Object[]{"royzhou",new String[]{"football","basketball"}}); System.out.println(sb);
//为name字段设置值
Field field = clazz.getDeclaredField("name"); field.setAccessible(true); //避免private不可访问抛出异常field.set(sb, "royzhou1985"); System.out.println("modify name using Field:=" + sb.getName() + "\n");
//列出类SimpleBean的所有方法
Method[] methods = clazz.getDeclaredMethods(); System.out.println("get methods of class SimpleBean:");
for(Method method : methods) {
if("setHobby".equals(method.getName())) {
//动态调用类的方法来为hobby设置值
method.invoke(sb, new Object[]{new String[]{"tennis","fishing"}});
}
System.out.println(method.getName());
}
System.out.println("\nset by invoke Method"); System.out.println(sb);
}
}
输出结果:
com.royzhou.bean.SimpleBean@757aef
name:=null
com.royzhou.bean.SimpleBean@d9f9c3
name:=royzhou
hobby:football,basketball,
modify name using Field:=royzhou1985
get methods of class SimpleBean:
setHobby
getHobby
getName
toString
setName
set by invoke Method
com.royzhou.bean.SimpleBean@d9f9c3
name:=royzhou1985
hobby:tennis,fishing
责任编辑:小草