通过反射对类进行实例化代码归结:
ABean a = BeanReflectUtils.instantiateBean(ABean.class);
a.setName("testName");
System.out.println(a.getName);
package com.demo.test.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
public class BeanReflectUtils {
public static <T> T instantiateBean(Class<T> tClass) throws Exception {
if (tClass == null) {
throw new NullPointerException("Class must not be null.");
}
if (tClass.isInterface()) {
throw new IllegalArgumentException("Class must not be interface.");
}
return instantiateBean(tClass.getDeclaredConstructor());
}
public static <T> T instantiateBean(Constructor<T> ctor, Object... args) throws InstantiationException, IllegalAccessException, InvocationTargetException {
/**
* make accessable
*/
if (!Modifier.isPublic(ctor.getModifiers()) ||
Modifier.isPublic(ctor.getModifiers()) && ctor.isAccessible()) {
ctor.setAccessible(true);
}
try {
/**
* 实例化
*/
return ctor.newInstance(args);
} catch (InstantiationException e) {
throw new InstantiationException(e.getMessage());
} catch (IllegalAccessException e) {
throw new IllegalAccessException(e.getMessage());
} catch (InvocationTargetException e) {
throw new InvocationTargetException(e.getCause());
}
}
}