当前位置: 首页 > wzjs >正文

网站建设公司网站模板下载装修设计培训机构

网站建设公司网站模板下载,装修设计培训机构,网站页面设计的重要性,同江佳木斯网站设计文章目录 示例5. 通过反射获得类的private、 protected、 默认访问修饰符的属性值。6. 通过反射获得类的private方法。7. 通过反射实现一个工具BeanUtils, 可以将一个对象属性相同的值赋值给另一个对象 接上篇: 示例 5. 通过反射获得类的private、 pro…

文章目录

  • 示例
    • 5. 通过反射获得类的private、 protected、 默认访问修饰符的属性值。
    • 6. 通过反射获得类的private方法。
    • 7. 通过反射实现一个工具BeanUtils, 可以将一个对象属性相同的值赋值给另一个对象

接上篇:

示例

5. 通过反射获得类的private、 protected、 默认访问修饰符的属性值。

import java.lang.reflect.Field;class Student {private String privateField = "私有属性值";protected String protectedField = "受保护属性值";String defaultField = "默认访问属性值"; // 包级私有public String publicField = "公有属性值";
}
public class ReflectionExample5 {public static void main(String[] args) {Student student = new Student();try {// 获取类的 Class 对象Class<?> clazz = Student.class;// ================== 访问私有属性 ==================Field privateField = clazz.getDeclaredField("privateField");privateField.setAccessible(true); // 解除私有访问限制String privateValue = (String) privateField.get(student);System.out.println("privateField: " + privateValue);// ================== 访问受保护属性 ==================Field protectedField = clazz.getDeclaredField("protectedField");protectedField.setAccessible(true); // 无需继承关系即可访问String protectedValue = (String) protectedField.get(student);System.out.println("protectedField: " + protectedValue);// ================== 访问默认(包级私有)属性 ==================Field defaultField = clazz.getDeclaredField("defaultField");defaultField.setAccessible(true);String defaultValue = (String) defaultField.get(student);System.out.println("defaultField: " + defaultValue);// ================== 访问公有属性 ==================// 方式 1:getDeclaredField + setAccessible(强制访问)Field publicField1 = clazz.getDeclaredField("publicField");publicField1.setAccessible(true); // 即使公有也强制解除限制(非必须)String publicValue1 = (String) publicField1.get(student);System.out.println("publicField(强制访问): " + publicValue1);// 方式 2:直接通过 getField 获取(不推荐,仅用于对比)Field publicField2 = clazz.getField("publicField");String publicValue2 = (String) publicField2.get(student);System.out.println("publicField(正常访问): " + publicValue2);} catch (NoSuchFieldException e) {System.err.println("字段不存在: " + e.getMessage());} catch (IllegalAccessException e) {System.err.println("访问权限失败: " + e.getMessage());}}
}

关键操作说明

  1. getDeclaredField() 方法
    - 作用:获取类中声明的所有字段(包括 private/protected/默认/public)
    - 需要手动调用 setAccessible(true) 来突破非 public 属性的访问限制。
  2. setAccessible(true)
    - 方法:Field.setAccessible(true)
    - 意义:解除 Java 的访问控制检查,允许操作非公有字段。
    - 安全性警告:此操作会绕过 Java 的封装机制,仅建议在框架等需要深度操作时使用。
  3. 字段值与对象实例的关联
    - 对于 实例字段:必须传入具体对象实例(如 student),通过 field.get(object) 获取值。
    - 对于 静态字段:可直接传入 null,如 field.get(null)。

6. 通过反射获得类的private方法。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;class MyClass3 {private String privateMethod(String param) {return "私有方法被调用,参数: " + param;}
}
public class ReflectionExample6 {public static void main(String[] args) {try {// 创建类的实例MyClass3 myObject = new MyClass3();// 获取Class对象Class<?> clazz = MyClass3.class;// 获取私有方法,需指定方法名和参数类型Method method = clazz.getDeclaredMethod("privateMethod", String.class);// 解除访问限制(关键步骤)method.setAccessible(true);// 调用方法,传入实例及参数String result = (String) method.invoke(myObject, "Hello");// 输出结果System.out.println("调用结果: " + result);} catch (NoSuchMethodException e) {System.err.println("方法未找到: " + e.getMessage());} catch (IllegalAccessException e) {System.err.println("非法访问: " + e.getMessage());} catch (InvocationTargetException e) {System.err.println("方法内部错误: " + e.getCause());}}
}

7. 通过反射实现一个工具BeanUtils, 可以将一个对象属性相同的值赋值给另一个对象

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;class BeanUtils {/*** 将源对象的属性值复制到目标对象(浅拷贝)* @param source 源对象* @param target 目标对象*/public static void copyProperties(Object source, Object target) {if (source == null || target == null) {throw new IllegalArgumentException("源对象和目标对象不能为 null");}// 获取源对象和目标对象的所有字段(包含父类字段)List<Field> sourceFields = getAllFields(source.getClass());List<Field> targetFields = getAllFields(target.getClass());for (Field sourceField : sourceFields) {// 查找目标对象中与源对象字段同名的字段Field targetField = findField(targetFields, sourceField.getName());if (targetField == null) continue;// 检查类型是否兼容(支持基本类型和包装类型)if (!isTypeCompatible(sourceField.getType(), targetField.getType())) continue;try {// 设置字段可访问性sourceField.setAccessible(true);targetField.setAccessible(true);// 复制值Object value = sourceField.get(source);targetField.set(target, value);} catch (IllegalAccessException e) {// 处理无法访问的异常System.err.println("字段复制失败: " + sourceField.getName() + " -> " + targetField.getName());}}}/*** 获取类及其父类的所有字段(非静态)*/private static List<Field> getAllFields(Class<?> clazz) {List<Field> fields = new java.util.ArrayList<>();while (clazz != null && clazz != Object.class) {fields.addAll(Arrays.stream(clazz.getDeclaredFields()).filter(f -> !isStatic(f)).collect(Collectors.toList()));clazz = clazz.getSuperclass();}return fields;}/*** 根据字段名从字段列表中查找字段*/private static Field findField(List<Field> fields, String fieldName) {return fields.stream().filter(f -> f.getName().equals(fieldName)).findFirst().orElse(null);}/*** 判断字段是否为静态*/private static boolean isStatic(Field field) {return java.lang.reflect.Modifier.isStatic(field.getModifiers());}/*** 判断源类型与目标类型是否兼容*/private static boolean isTypeCompatible(Class<?> sourceType, Class<?> targetType) {// 处理基本类型与包装类型的兼容(例如 int -> Integer)if (sourceType.isPrimitive()) {return targetType.isPrimitive() ? sourceType.equals(targetType) : getWrapperType(sourceType).equals(targetType);} else if (targetType.isPrimitive()) {return getWrapperType(targetType).equals(sourceType);} else {return targetType.isAssignableFrom(sourceType);}}/*** 获取基本类型对应的包装类型*/private static Class<?> getWrapperType(Class<?> primitiveType) {if (primitiveType == int.class) return Integer.class;if (primitiveType == long.class) return Long.class;if (primitiveType == boolean.class) return Boolean.class;if (primitiveType == byte.class) return Byte.class;if (primitiveType == char.class) return Character.class;if (primitiveType == short.class) return Short.class;if (primitiveType == double.class) return Double.class;if (primitiveType == float.class) return Float.class;return primitiveType;}
}// 父类
class Person {protected String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}// 子类
class Employee extends Person {private double salary;private Integer departmentId;public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public Integer getDepartmentId() {return departmentId;}public void setDepartmentId(Integer departmentId) {this.departmentId = departmentId;}
}// 目标类
class EmployeeDTO {private String name;private int age;        // 基本类型private Double salary;  // 包装类型private Integer departmentId;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Double getSalary() {return salary;}public void setSalary(Double salary) {this.salary = salary;}public Integer getDepartmentId() {return departmentId;}public void setDepartmentId(Integer departmentId) {this.departmentId = departmentId;}
}public class ReflectionExample7 {public static void main(String[] args) {// 准备数据Employee emp = new Employee();emp.name = "张三";emp.setAge(30);emp.setSalary(15000.5);emp.setDepartmentId(101);// 目标对象EmployeeDTO dto = new EmployeeDTO();// 复制属性BeanUtils.copyProperties(emp, dto);// 验证结果System.out.println("DTO.name: " + dto.getName());System.out.println("DTO.age: " + dto.getAge());System.out.println("DTO.salary: " + dto.getSalary());System.out.println("DTO.departmentId: " + dto.getDepartmentId());}
}

文章转载自:

http://6CB0bOzb.zfxrx.cn
http://Ej58mamH.zfxrx.cn
http://hoAxWYMQ.zfxrx.cn
http://908gbBTf.zfxrx.cn
http://EacsjMCq.zfxrx.cn
http://Cqu1Mq3g.zfxrx.cn
http://jDMHMhuw.zfxrx.cn
http://UyGhV04X.zfxrx.cn
http://mKuMHbde.zfxrx.cn
http://OQIE6fBt.zfxrx.cn
http://gzKUPD83.zfxrx.cn
http://4B0jarXG.zfxrx.cn
http://AzXr6rGK.zfxrx.cn
http://9LWJzXyy.zfxrx.cn
http://SUX7mIdN.zfxrx.cn
http://E5Sp0Jam.zfxrx.cn
http://MlCkQ8f0.zfxrx.cn
http://2rJEXXSI.zfxrx.cn
http://fo8WBkOG.zfxrx.cn
http://s0AysFPy.zfxrx.cn
http://bLpcoeXS.zfxrx.cn
http://OjUCk3VZ.zfxrx.cn
http://dzPslEsO.zfxrx.cn
http://pESbH5hh.zfxrx.cn
http://7rbkVeBJ.zfxrx.cn
http://wVbyZozi.zfxrx.cn
http://Sjrt3xWK.zfxrx.cn
http://R9sEykVS.zfxrx.cn
http://SVj97OL9.zfxrx.cn
http://srEBfsZs.zfxrx.cn
http://www.dtcms.com/wzjs/746776.html

相关文章:

  • 网站数据库分离怎么做班级网站建设html制作
  • 网站标题在线制作成都住房和城乡建设部网站查询
  • 江苏推广网站建设业务什么做网站站群
  • 江苏省建设执业网站网页传奇开服表
  • 平台和网站有什么区别北京网站优化招聘
  • 眉山建设局网站在线简历模板
  • 网站开发对cpu要求高吗上海500强企业排名
  • 做网站带来好处一键生成logo免费在线网页
  • 商丘网站建设制作网站首页布局自适应
  • 招聘网站做招聘顾问用dedecms做的网站 脚本是什么
  • 装修公司的网站怎么做大兴区企业网站建设
  • 个人网站开发要多久怎么样自己做企业网站
  • 网站开发用php好吗哈尔滨干肠制作
  • ps做网站原形哪个平台做推广效果好
  • 利为汇wordpress谷歌seo技巧
  • 万网网站备案管理swiper手机网站案例
  • wordpress和站点什么是企业形象设计
  • 深圳龙岗建网站服装网站页面设计
  • 虚拟主机建设网站绑定域名dw做网站学习解析
  • 网站建设开题报告中的问题销售平台的重要性
  • 游戏网站 模板编程培训心得
  • 网站的系统建设方式有哪些方面如何做qq钓鱼网站
  • 网站建设开发设计营销公司厦门龙华品牌网站制作
  • asp静态网站wordpress 焦点图
  • 北京网站开发月薪手机版网站建设
  • 网站建设和网络维护帮你做决定的网站
  • led高端网站建设网站上怎么做弹目提醒
  • 安顺网站设计wordpress怎么搬站
  • 建站服务是什么学网站建设多少学费
  • 淘宝客推广平台湖南纯手工seo电话