打卡-反射基础(二)
反射
1.1获取Class对象的三种方式-(Class 是一个类:一个描述类的类)
1.通过类名获取 类名.class
2.通过对象获取 对象名.getClass()
3.通过全类名获取 Class.forName(全类名)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Person { 2 String name; 3 int age; 4 public void setName(String name) { 5 this.name = name; 6 } 7 public void setAge(int age) { 8 this.age = age; 9 } 10 public Person(String name, int age) { 11 super(); 12 this.name = name; 13 this.age = age; 14 } 15 public Person() { 16 super(); 17 } 18 }
第一种:
1 Class calzz=Person.class;
第二种:(这种的写法实际意义不大,因为已经清楚了类别,如果传进来的是一个你所不知道的Bbject类,这种方法就可行)
1 Person Person = new Person(); 2 Class calzz=Person.getClass();
第三种:
1 Class calzz = Class.forName("com.atguigu.java.fanshe.Person");
2.1Reflection(反射)
是Java被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的內部信息,并能直接操作任意对象的内部属性及方法。
Java反射机制主要提供了以下功能:
- 在运行时构造任意一个类的对象
- 在运行时获取任意一个类所具有的成员变量和方法
- 在运行时调用任意一个对象的方法(属性)
- 生成动态代理
封装了描述方法的 Method
描述字段的 Filed
描述构造器的 Constructor 等属性.
2.2获取方法
第一种:方法数组
getMethods():获取本类以及父类的公共方法或者其接口中所有的公共方法(不包括私有方法)
1 //getMethods() 2 Method[] methods = calzz.getMethods(); 3 for(Method method:methods){ 4 System.out.print(" "+method.getName()); 5 }
getDeclareMethods():获取本类的所有方法包括私有方法,但是不包括继承的方法及其接口
1 Method[] methods = clazz.getDeclaredMethods(); 2 for(Method method:methods){ 3 System.out.print(" "+method.getName()); 4 }
第二种:指定方法
// 方法public void setName(String name) { } Method method = calzz.getDeclaredMethod("wait", String.class); System.out.println(method); // 于方法public void setAge(Integer age) { } Method method = calzz.getDeclaredMethod("wait", Integer.class); System.out.println(method);