转自http://uuhorse.iteye.com/blog/1706466
① 创建对象
如果知道一个类型,很容易使用new操作符创建一个类的实例。但是如果在编译时并不知道具体要实例化的是哪个类的对象,如何创建该实例呢?
Java中提供Class.forName(String className)从一个字符串(含包的类全名称)加载一个类,再利用newInstance方法创建该类的实例。
//动态创建类对象
public static Object createObject(String className) {
Object object = null;
try {
Class classDefinition = Class.forName(className);
object = classDefinition.newInstance();
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
return object;
}
//使用Constructor动态创建对象
public static Object createObject(Constructor constructor, Object[] arguments) {
System.out.println("Constructor: " + constructor.toString());
Object object = null;
try {
object = constructor.newInstance(arguments);
System.out.println("Object: " + object.toString());
return object;
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (IllegalArgumentException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
}
return object;
}
② 获取/设置字段值
// 获取字段值
static void getFiledValue(Object o, String filedName) {
Class c = o.getClass();
Field filed;
Object value;
try {
filed = c.getField(filedName);
// filed = c.getDeclaredField(filedName);
// filed.setAccessible(true); //修改字段访问权限
value = filed.get(o); //可使用getInt、getLong等(若知晓字段基本类型)
System.out.println(filedName + ": " + value.toString());
} catch (NoSuchFieldException e) {
System.out.println(e);
} catch (SecurityException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
}
}
// 修改字段值
public static void setFieldValue(Object o, String filedName, Object value) {
Field filed;
Class c = o.getClass();
try {
filed = c.getField(filedName);
// filed = c.getDeclaredField(filedName);
// filed.setAccessible(true); //修改字段访问权限
filed.set(o, value); //可使用setInt、setLong等(若知晓字段基本类型)
} catch (NoSuchFieldException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
}
}
//动态调用方法
public static Object callMethod(Object o, String methodName,
Class paramsType[], Object paramsValue[]) {
Object result = null;
Class c;
Method method;
try {
c = o.getClass();
method = c.getMethod(methodName, paramsType);
// method = c.getDeclaredMethod(methodName, paramsType);
// method.setAccessible(true);
result = method.invoke(o, paramsValue);
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
}
return result;
}