学习打卡第五天


1
import java.lang.reflect.*; 2 3 public class ReflexTest1 { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Class<?> c1 = Student.class; 8 //得到该类中的所有成员变量,包括private变量 9 Field[] fileds = c1.getDeclaredFields();//Field类表示字段 10 System.out.println("得到该类中的所有成员变量:"); 11 for(Field field :fileds) 12 { 13 System.out.println(field.getName()); 14 } 15 System.out.println(""); 16 System.out.println(""); 17 //得到该类中public的方法,包括Object类所包括的方法 18 Method[] methods = c1.getMethods();//method类表示方法 19 System.out.println("得到该类中public的方法包括Object类中的方法:"); 20 for(Method method : methods) 21 { 22 System.out.println(method.getName()); 23 } 24 System.out.println(""); 25 System.out.println(""); 26 try { 27 Field f1,f2; 28 //获得指定的成员变量 29 f1 = c1.getField("ID"); 30 System.out.println(f1); 31 //获得指定的私有成员变量 32 f2 = c1.getDeclaredField("age"); 33 System.out.println(f2); 34 //建立一个Object对象,用来存放Student类对象 35 Object o = new Student("hhh",111,'h'); 36 //启用和禁用访问安全检查的开关,值为 true 37 //则表示反射的对象在使用时应该取消 java 语言的访问检查;反之不取消 38 f2.setAccessible(true); 39 // 将o对象中的f2成员变量赋值为220 40 f2.set(o, 220); 41 // 得到o对象中的f2成员变量并且输出 42 System.out.println(f2.get(o)); 43 //使用反射机制可以打破封装性,导致了java对象的属性不安全。 44 } catch (NoSuchFieldException | SecurityException e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 } catch (IllegalArgumentException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 } catch (IllegalAccessException e) { 51 // TODO Auto-generated catch block 52 e.printStackTrace(); 53 } 54 System.out.println(); 55 System.out.println(); 56 System.out.println("获得所有的构造函数:"); 57 //获得所有的构造函数 58 Constructor[] constructors = c1.getConstructors(); 59 for(Constructor constructor : constructors) 60 { 61 System.out.println(constructor); 62 } 63 64 } 65 66 } 67 class Student 68 { 69 public int ID; 70 private String name ; 71 private int age ; 72 private char sex ; 73 public Student(String name , int age , char sex) 74 { 75 this.name = name; 76 this.age = age; 77 this.sex = sex; 78 } 79 public Student(String name , int age , char sex, int ID) 80 { 81 this.name = name; 82 this.age = age; 83 this.sex = sex; 84 this.ID = ID; 85 } 86 public Student() 87 { 88 89 } 90 public void show() 91 { 92 93 } 94 private void print() 95 { 96 System.out.println("姓名:"+this.name); 97 System.out.println("年龄:"+this.age); 98 System.out.println("性别:"+this.sex); 99 } 100 public String getName() { 101 return name; 102 } 103 public void setName(String name) { 104 this.name = name; 105 } 106 public int getAge() { 107 return age; 108 } 109 public void setAge(int age) { 110 this.age = age; 111 } 112 public char getSex() { 113 return sex; 114 } 115 public void setSex(char sex) { 116 this.sex = sex; 117 } 118 119 }

以上是今日学习的java反射内容,可以利用反射,知道该类中的成员变量,哪怕是private类型也能获取到,也可以通过反射去获取类里面的方法,可以通过反射给对象里封装好的变量赋值,也可以去得到那个值,还能够去获得构建函数,一个个都输出来。

猜你喜欢

转载自www.cnblogs.com/sucker/p/10611929.html