Java 反射获取父类实例化对象中的值

2019-10-30 18:48:52 浏览数 (1)

想通过反射将父类实例化一个子类,使用如下方案:

代码语言: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);
}

0 人点赞