想通过反射将父类实例化一个子类,使用如下方案:
代码语言:javascript复制try {
Field[] fields = super.getClass.getDeclaredFields();
for (Field field : fields) {
field.setAcessible(true);
Method method = super.getClass().getDeclaredMethod("get" upperHeadChar(field.getName()));
Object obj = method.invoke(super);
field.set(this, obj);
}
} catch (NoSuchMethodException | IllegalAcessException | InvocationTargetException e){
e.printStackTrace();
}
private static String upperHeadChar(String in){
String head = in.substring(0,1);
return head.toUpperCase() in.substring(1);
}