反射调用成员属性
程序员文章站
2023-11-16 16:23:04
1.获取类中的成员属性信息 运行结果: 2.反射操作成员属性内容: 运行结果: 如果不解除封装,会抛如下异常: 3.获取指定属性类型: 运行结果: ......
成员属性保存了一个对象的所有信息,通过反射可以实现成员属性的赋值与取值操作,本课程主要讲解了属性的直接操作,以及封装性取消等操作。
1.获取类中的成员属性信息
1 package com.youtube.demo; 2 3 import java.lang.reflect.field;; 4 5 interface ichannelservice{ 6 public static final string name = "youtube"; 7 } 8 abstract class absbase{ 9 protected static final string base = "www.youtube.com"; 10 private string info = "hello, youtube"; 11 } 12 class member extends absbase implements ichannelservice{ 13 private string name; 14 private int age; 15 } 16 public class javareflectdemo { 17 public static void main(string[] args) { 18 class <?> cls = member.class; 19 { 20 field fields[] = cls.getfields(); 21 for(field field:fields) { 22 system.out.println(field); 23 } 24 } 25 system.out.println("----------------华丽的分割线------------------"); 26 { 27 field fields[] = cls.getdeclaredfields(); 28 for(field field:fields) { 29 system.out.println(field); 30 } 31 } 32 } 33 }
运行结果:
public static final java.lang.string com.youtube.demo.ichannelservice.name ----------------华丽的分割线------------------ private java.lang.string com.youtube.demo.member.name private int com.youtube.demo.member.age
2.反射操作成员属性内容:
1 package com.facebook.demo; 2 import java.lang.reflect.field; 3 class member{ 4 private string name; 5 } 6 public class javareflectdemo { 7 public static void main(string[] args) throws exception { 8 class<?> cls = member.class; 9 object obj = cls.getdeclaredconstructor().newinstance(); 10 field namefield = cls.getdeclaredfield("name"); 11 namefield.setaccessible(true);//解除封装 12 namefield.set(obj, "小李老师"); 13 system.out.println(namefield.get(obj)); 14 } 15 }
运行结果:
小李老师
如果不解除封装,会抛如下异常:
exception in thread "main" java.lang.illegalaccessexception: class com.facebook.demo.javareflectdemo cannot access a member of class com.facebook.demo.member with modifiers "private" at java.base/jdk.internal.reflect.reflection.newillegalaccessexception(reflection.java:355) at java.base/java.lang.reflect.accessibleobject.checkaccess(accessibleobject.java:639) at java.base/java.lang.reflect.field.checkaccess(field.java:1075) at java.base/java.lang.reflect.field.set(field.java:778) at com.facebook.demo.javareflectdemo.main(javareflectdemo.java:11)
3.获取指定属性类型:
1 package com.facebook.demo; 2 import java.lang.reflect.field; 3 class member{ 4 private string name; 5 } 6 public class javareflectdemo { 7 public static void main(string[] args) throws exception { 8 class<?> cls = member.class; 9 object obj = cls.getdeclaredconstructor().newinstance(); 10 field namefield = cls.getdeclaredfield("name"); 11 system.out.println(namefield.gettype().getname()); 12 system.out.println(namefield.gettype().getsimplename()); 13 } 14 }
运行结果:
java.lang.string string
上一篇: Ai绘制超简单的认证标志