三个反射的例子

例子一:

package com.test;

import java.lang.reflect.Method;

public class DumpMethods {
public static void main(String[] args) throws Exception {
//Class类是java反射的入口点
Class<?> classType = Class.forName(args[0]);
Method[] methods = classType.getDeclaredMethods();
for(Method method : methods){
System.out.println(method);
}
}
}

例子二:

package com.test;

import java.lang.reflect.Method;

public class InvokeTester {
public int add(int param1,int param2){
return param1 + param2;
}
public String echo(String msg){
return "hello" + msg;
}
public static void main(String[] args) throws Exception {
Class<?> classType = InvokeTester.class;
Object invokeTester = classType.newInstance();
Method addMethod = classType.getMethod("add",new Class[] {int.class, int.class});
Object result = addMethod.invoke(invokeTester,new Object[]{100,200});
System.out.println((Integer)result);
}
}

例子三:

package com.test;

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

public class ReflectTester {

public Object copy(Object object) throws Exception{
Class<?> classType = object.getClass();
System.out.println(classType.getName());
Object objectCopy = classType.getConstructor(new Class[] {})
.newInstance(new Object[] {});
Field[] fields = classType.getDeclaredFields();
for(int i = 0;i < fields.length;++i){
Field field = fields[i];
String fieldName = field.getName();
String firstLetter = fieldName.substring(0,1).toUpperCase();
String getMethodName = "get" + firstLetter + fieldName.substring(1);
String setMethodName = "set" + firstLetter + fieldName.substring(1);
Method getMethod = classType.getMethod(getMethodName , new Class[]{});
Method setMethod = classType.getMethod(setMethodName , new Class[]{field.getType()});

Object value = getMethod.invoke(object,new Object[]{});
System.out.println(fieldName + ":" + value);

setMethod.invoke(objectCopy,new Object[]{value});
}
return objectCopy;
}
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.setId(new Long(1));
customer.setAge(20);
customer.setName("zhangsan");
Customer customerCopy = (Customer)new ReflectTester().copy(customer);
System.out.println(customerCopy.getId() + "," +
customerCopy.getName() + "," +customerCopy.getAge());
}
}

class Customer{
public Customer(){

}
private Long id;

private String name;

private int age;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}

你可能感兴趣的:(反射)