java通过反射动态调用类的方法

//随便写两个类,可以实现接口,我的需求是不能实现接口,因为没个类中的方法名称都不同,也不存在相同的方法名称
public class Fanshe1{
	
	public String selectValue1(String s){
		return s+"有效";
	}
	public String selectValue2(String s){
		return s+"有效";
	}
}
public class Fanshe2 {
	
	public String selectValue1(String s){
		System.out.println("selectValue1已执行");
		return s+"有效";
	}
	public String selectValue2(String s){
		System.out.println("selectValue2已执行");

		return s+"有效";
	}
}
public class GitTest {
	public static void main(String[] args) {
		java.util.List tt = init();
		for(int i=0,j=tt.size();i t_class =  Class.forName(classz);
				Method m = t_class.getDeclaredMethod(method, String.class);
				Object object = m.invoke(t_class.newInstance(),test.getValue());
				System.out.println(object);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//初始化数据,我的需求是这些都是从数据库中查询出来的实体
	public static List init(){
		Test t1 = new Test();
		t1.setName("var1");
		t1.setValue("var11");
		t1.setClassName("com.git.common.Fanshe1#selectValue1");
		Test t2 = new Test();
		t2.setName("var2");
		t2.setValue("var22");
		t2.setClassName("com.git.common.Fanshe1#selectValue2");
		Test t11 = new Test();
		t11.setName("var111");
		t11.setValue("var1111");
		t11.setClassName("com.git.common.Fanshe2#selectValue1");
		Test t22 = new Test();
		t22.setName("var222");
		t22.setValue("var2222");
		t22.setClassName("com.git.common.Fanshe2#selectValue2");
		
		java.util.List tt = new ArrayList();
		tt.add(t1);
		tt.add(t2);
		tt.add(t11);
		tt.add(t22);
		return tt;
	}
}
class Test{
	private String name;
	private String value;
	private String className;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
}



你可能感兴趣的:(JAVA)