在数据库开发中会遇到把数据库记录绑定到bean对象中. 因此需要在dao 层获取对应的bean的实例. 然后把记录数据填充到实例中.实际的方法其实有多种.这提供了一个隐式方式获取实例的方法
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class MainRunner {
/**
* @param args
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Factory<Base> instance=new Factory<Base>(){};
Base b=instance.createObject();
}
}
abstract class Factory<T>{
protected Class<?> getType(){
Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
Type type= ((ParameterizedType) superclass).getActualTypeArguments()[0];
//return (Class<?>) ((ParameterizedType) type).getRawType();
return (Class<?>) type;
}
public T createObject() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
//return getType().newInstance();
return (T)getType().getConstructor().newInstance();
}
}
class Base{
public Base(){};
}