成员属性保存了一个对象的所有信息,通过反射可以实现成员属性的赋值与取值操作,本课程主要讲解了属性的直接操作,以及封装性取消等操作。
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