JAvaの反射使用
1710 ワード
シーン:javaの反射使用、比較的良いフレームワークを開発する際に必要な道1.java反射
2.テスト例
以上、TKS.
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.