反射工具
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import com.test.fanshe.TestFanShe;
/**
* java.lang.reflect
* 反射测试
* @author 房金玮
*
*/
public class ReflectUtil {
public static void main(String[] args) {
// TODO Auto-generated method stub
String className="com.test.fanshe.TestFanShe";
//参数必须是对象类型 不支持数组 将对象序列化到数据库中
// classInstanceForMethodByParameter(className,"testPringMap",map);
// classInstanceForMethodByParameter(className,"testPrintString","房子");
//测试方法重载
classInstanceForMethodByParameter(className,"testPrintString",new Object[]{1,""});
}
public static void classInstanceForMethodByParameter(String className,String methodStr,Object[] parameter){
try {
Class calss=Class.forName(className);
Method[] methods=calss.getMethods();
Class[] parameterTypes=null;
for(Method method:methods){
if(method.getName().equals(methodStr)){
Class[] parameterTypesNow=method.getParameterTypes();
if(parameterTypesNow.length==parameter.length){
boolean flg=true;
for(int i=0;i<parameter.length;i++){
if(!parameterTypesNow[i].equals(parameter[i].getClass())){
flg=false;
break;
}
}
if(flg){
parameterTypes=parameterTypesNow;
}
}
}
if(parameterTypes!=null){
break;
}
}
try {
//执行有参数的构造方法
Method method = calss.getMethod(methodStr, parameterTypes);
method.invoke(calss.newInstance(), parameter);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
// try {
// //执行无参数方法
// Method method = calss.getMethod(methodStr, new Class[]{});
// method.invoke(calss.newInstance(), new Object[]{});
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// }
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
测试类
package com.test.fanshe;
import java.util.Iterator;
import java.util.Map;
public class TestFanShe {
public String namepublic;
public String getNamepublic() {
return namepublic;
}
public void setNamepublic(String namepublic) {
this.namepublic = namepublic;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void testPrintString(){
System.out.println("testPrintString:");
}
public void testPrintString(String name){
System.out.println("testPrintString:name");
}
public void testPrintString(String name,Integer intstr){
System.out.println("testPrintString:String name,Integer intstr");
}
public void testPrintString(Integer intstr,String name){
System.out.println("testPrintString:Integer intstr,String name");
}
public void testPringMap(Map map){
Iterator<String> iterator=null;
for(iterator=map.keySet().iterator();iterator.hasNext();){
System.out.println(map.get(iterator.next()));
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.getClass().getName()+"@"+"namepublic:"+this.namepublic+"&name:"+this.name;
}
}