public class testbean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public testbean()
{
this.name=name;
}
public void testclass(String name)
{
System.out.println("我是测试方法"+name);
}
}
一下为主方法
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class reflect {
public static void main(String[] args) throws IllegalArgumentException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException
{
ss();
}
public static void ss() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Class clazz=Class.forName("testbean");
testbean tb=(testbean) clazz.newInstance();//实例化获取的class对象,获得对象
tb.testclass("name参数");
//获取属性
Field[] f=clazz.getDeclaredFields();
Method[] m=clazz.getDeclaredMethods();
//打印方法名
for(Method method:m)
System.out.println(method.getName());
Class<testbean> bean=testbean.class;
testbean tbean=new testbean();
try {
Field beanfield=bean.getDeclaredField("name");
beanfield.setAccessible(true);
beanfield.set(tbean, "sunxh");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
============================================================
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Testreflection {
public static void main(String[] args) {
Person p=new Person();
// ReflectionDemo re=new ReflectionDemo();
ReflectionDemo re=new ReflectionDemo(p);
/*
* 构造方法
* 获得Class对象方式之三通过类的class属性获得
*/
Class cla=Person.class;
Method[] method=cla.getDeclaredMethods();//利用Class对象对象cla的自审,返回方法对象集合
System.out.println("******获取方法信息******");
for(Method m:method){
System.out.println(method.toString());
}
System.out.println("******获取方法信息结束******");
Field[] fields=cla.getDeclaredFields();
System.out.println("******获取属性信息******");
for(Field field:fields){
System.out.println(field.toString());
}
System.out.println("******获取属性信息结束******");
====================================================================
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Testreflection {
public static void main(String[] args) {
Person p=new Person();
// ReflectionDemo re=new ReflectionDemo();
ReflectionDemo re=new ReflectionDemo(p);
/*
* 构造方法
* 获得Class对象方式之三通过类的class属性获得
*/
Class cla=Person.class;
Method[] method=cla.getDeclaredMethods();//利用Class对象对象cla的自审,返回方法对象集合
System.out.println("******获取方法信息******");
for(Method m:method){
System.out.println(method.toString());
}
System.out.println("******获取方法信息结束******");
Field[] fields=cla.getDeclaredFields();
System.out.println("******获取属性信息******");
for(Field field:fields){
System.out.println(field.toString());
}
System.out.println("******获取属性信息结束******");
}
}