package com.jason.base.reflect;
import java.lang.reflect.Method;
/**
* 反射(运行期的行为)
* @author Administrator
*
*/
public class ReflectDemo
{
/**
* @param args
*/
public static void main(String[] args) throws Exception
{
Class<?> classType = Class.forName("java.lang.String");// 获取Class
Method [] methods = classType.getDeclaredMethods();
for(Method m : methods)
System.out.println(m);
/
classType = ReflectDemo.class;// 获取Class
Object obj = classType.newInstance();// 获取ReflectDemo实例
Method m = classType.getMethod("add", new Class[]{int.class, int.class});
Object result = m.invoke(obj, new Object[]{1,2});
System.out.println(result);
m = classType.getMethod("echo", new Class[]{String.class});
result = m.invoke(obj, new Object[]{"Sam"});
System.out.println(result);
}
public int add(int param1, int param2)
{
return param1 + param2;
}
public String echo(String name)
{
return "Hello, " + name;
}
}
package com.jason.base.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 使用对象.getClass()返回Class对象,使用Constructor构造带有参数的对象实例化
* @author Administrator
*
*/
public class ReflectMethod
{
/**
* 完成对象的copy功能
* @param obj
* @return
* @throws Exception
*/
public static Object copy(Object obj) throws Exception
{
Class<?> classType = obj.getClass();
/*
Constructor c = classType.getConstructor(new Class[]{String.class, int.class});
Object o = c.newInstance(new Object[]{"sam", 3});
return o;
*/
Object copyObj = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
Field [] fields = classType.getFields();
for(Field f : fields)
{
String name = f.getName();
String firstLetter = name.substring(0, 1).toUpperCase();
String setMethodName = "set" + firstLetter + name.substring(1);
String getMethodName = "get" + firstLetter + name.substring(1);
Method getMethod = classType.getMethod(getMethodName, new Class[]{});
Method setMethod = classType.getMethod(setMethodName, new Class[]{f.getType()});
Object value = getMethod.invoke(obj, new Object[]{});
setMethod.invoke(copyObj, new Object[]{value});
}
return copyObj;
}
public static void main(String[] args) throws Exception
{
Customer c1 = new Customer();
c1.setId(1);
c1.setAge(22);
c1.setName("sam");
Customer c2 = (Customer)copy(c1);
System.out.println(c2);
}
}
package com.jason.base.reflect;
public class Customer
{
private long id;
private String name;
private int age;
public Customer()
{
}
public Customer(String name, int age)
{
this.name = name;
this.age = age;
}
/**
* @return the id
*/
public long getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId(long id)
{
this.id = id;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the age
*/
public int getAge()
{
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return id +" ," + name + ", " +age;
}
}