package com.example.test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.util.Log;
public class ClsUtils {
private static final String TAG = "XXX";
/**
*
* @param className
* 需要反射类的名字
* @return
* @throws ClassNotFoundException
*/
public static Class creatClassObject(String className)
throws ClassNotFoundException {
Class cls = Class.forName(className);
return cls;
}
/**
*
* @param cls
* 反射类
* @param key
* 系统属性key值
* @param val
* key对应的value值
*/
public static void setSystemProperties(Class cls, String key, String val) {
try {
Method hideMethod = cls.getMethod("set", new Class[] {
String.class, String.class });
Object object = cls.newInstance();
hideMethod.invoke(object, new Object[] { new String(key),
new String(val) });
Log.e(TAG, "111111111111111111");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 得到系统属性key值对应的value值
*
* @param cls
* 反射类
* @param key
* 系统属性key值
* @return
*/
public static String getSystemProperties(Class cls, String key) {
String value = null;
try {
Method hideMethod = cls.getMethod("get", String.class);
Object object = cls.newInstance();
value = (String) hideMethod.invoke(object, key);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return value;
}
/**
* 查看反射类的 所有方法和常量
*
* @param cls
*/
static public void printMethod(Class cls) {
Log.e(TAG, "--------printMethod-------");
Method[] hideMethod = cls.getMethods();
// 取得所有方法
int i = 0;
for (i = 0; i < hideMethod.length; i++) {
Log.e(TAG, hideMethod[i].getName().toString());
}
Log.e(TAG, "--------print static var-------");
// 取得所有常量
Field[] allFields = cls.getFields();
for (i = 0; i < allFields.length; i++) {
Log.e(TAG, allFields[i].getName());
}
}
}
java反射工具类
最新推荐文章于 2024-10-03 08:24:38 发布