EKT反射

什么是反射:

反射是框架的基础,框架的底层实现很多都是基于反射,反射使得java语言具有动态特性;

在JDK中,主要由以下类来实现Java反射机制,这些类都位于java.lang.reflect包中:

Class类:代表一个类。

Field 类:代表类的成员变量(成员变量也称为类的属性)。

Method类:代表类的方法。

Modifier类:代表修饰符。

lConstructor 类:代表类的构造方法。

Array类:提供了动态创建数组,以及访问数组的元素的静态方法。

反射Student类的所有构造方法:

package demo2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

public class Demo2 {

   /**
    * @param args
    * @throws NoSuchMethodException 
    * @throws SecurityException 
    * @throws InvocationTargetException 
    * @throws IllegalAccessException 
    * @throws InstantiationException 
    * @throws IllegalArgumentException 
    */
   public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
      // 反射String类的所有构造方法
      Class clz = Student.class;

      System.out.println("所有构造方法");
      // Constructor[] cons = clz.getConstructors();
      Constructor[] cons = clz.getDeclaredConstructors();
      for (Constructor con : cons) {
         // System.out.println("访问修饰权限:" +
         // Modifier.toString(con.getModifiers()));
         // System.out.println("方法名:" + con.getName());
         // System.out.println("****************************");
         System.out.println(Modifier.toString(con.getModifiers()) + " "
               + con.getName());
      }

      
      //找无参的构造方法    Student s = new Student();
      Constructor con = clz.getDeclaredConstructor();
      Object obj = con.newInstance();
      System.out.println(obj);
      
      //找带string,int类型参数的构造方法 Student s = new Student("zhangsan",12)
      con = clz.getDeclaredConstructor(String.class, int.class);
      obj = con.newInstance("zhangsan", 12);
      System.out.println(obj);
      
      con = clz.getDeclaredConstructor(String.class);
      
      
   }

}

心得:

  人生如一本书,应该多一些精彩的细节,少一些乏味的字眼;人生如一支歌,应该多一些昂扬的旋律,少一些忧伤的音符;人生如一幅画,应该多一些亮丽的色彩,少一些灰暗的色调。

原文地址:https://www.cnblogs.com/javacyq/p/13555648.html