java的反射使用

场景:java的反射使用,开发比较好的框架时候,必须之路
1.java反射

public class ReflectUtils {

	/** 反射操作 */
	public static Object doReflectWork(final String ClassName,final String methodName, final Object[] obj) {
		try {
			Class cls = Class.forName(ClassName);
			Method method = null;
			for (Method method1 : cls.getMethods()) {
				if (method1.getName().equals(methodName)) {
					method = method1;
				}
			}
			if (method != null) {
				int modifers = method.getModifiers();
				/** 反射包提供的静态方法判断,静态方法直接调用 */
				if (Modifier.isStatic(modifers)) {
					method.invoke(cls, obj);
					/** 非静态方法需要创建对象 */
				} else {
					method.invoke(cls.newInstance(), obj);
				}
				return "调用成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

2.测试示例

public class TestReflect {
	
	public static void  doworkCity(String obj1,String obj2){
 	System.out.println("输出参数1: " + obj1.toString() );
 	System.out.println("输出参数2: " + obj2.toString() );
	}	
	public void  doworkProvince(String obj){
		System.out.println("输出参数: " + obj.toString());
	}
	//com.zbz.test.TestReflect
	public static void main(String [] args){	
		Object[] objStatic = new Object[]{"静态测试成功!","静态测试2"};
		System.out.println("测试开始......");
		System.out.println("调用静态方法:");
		ReflectUtils.doReflectWork("com.zbz.test.TestReflect", "doworkCity", objStatic);
		System.out.println("调用非静态方法:");
		Object[] obj2 = new Object[]{"非静态测试成功!"};
		ReflectUtils.doReflectWork("com.zbz.test.TestReflect", "doworkProvince", obj2);
		System.out.println("测试结束......");
	}
}

以上,TKS.

你可能感兴趣的:(Java)