当前位置:首页 > Java API 与类库手册 > 正文

Java优学网Field反射入门解析:轻松掌握私有字段访问与配置加载技巧

public class Student {

private String name = "张三";
private int score = 95;

}

// 反射访问示例 public class FieldReflectionDemo {

public static void main(String[] args) throws Exception {
    Student student = new Student();
    Class<?> clazz = student.getClass();
    
    Field nameField = clazz.getDeclaredField("name");
    nameField.setAccessible(true);
    
    String nameValue = (String) nameField.get(student);
    System.out.println("学生姓名:" + nameValue);
    
    // 修改私有字段值
    nameField.set(student, "李四");
    System.out.println("修改后姓名:" + nameField.get(student));
}

}

public class ConfigLoader {

public static <T> T loadConfig(Class<T> clazz, Properties props) {
    try {
        T instance = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (props.containsKey(fieldName)) {
                String value = props.getProperty(fieldName);
                // 根据字段类型进行类型转换
                setFieldValue(field, instance, value);
            }
        }
        return instance;
    } catch (Exception e) {
        throw new RuntimeException("配置加载失败", e);
    }
}

}

// 直接访问:约1-2纳秒 user.name = "张三";

// 反射访问:约100-200纳秒 Field nameField = User.class.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(user, "张三");

Java优学网Field反射入门解析:轻松掌握私有字段访问与配置加载技巧

你可能想看:

相关文章:

文章已关闭评论!