反射

 反射

          反射机制是在运行状态中: 对于任意一个类,都能够知道这个类的所有属性和方法;

                                                      对于任意一个对象,都能够调用它的任意一个方法和属性;

                        反射提供的功能: 在运行时判断任意一个对象所属的类;

                                                       在运行时构造任意一个类的对象;

                                                       在运行时判断任意一个类所具有的成员变量和方法;

                                                       在运行时调用任意一个对象的方法; 生成动态代理。

package reflect;

public interface MyInterface
{
   void interfaceMethod();
}
package reflect;

public interface MyInterface2
{
   void inteface2Method();
}
package reflect;

public class Person implements MyInterface,MyInterface2
{
private  int id;
private String name;
private int age;
public Person(){}
   public Person(int id) {
       this.id = id;
  }
   public Person(int id, String name, int age) {
       this.id = id;
       this.name = name;
       this.age = age;
  }
   private Person(String name){
    this.name=name;
}
   
   public int getId() {
       return id;
  }

   public void setId(int id) {
       this.id = id;
  }
   public String getName() {
       return name;
  }
   public void setName(String name) {
       this.name = name;
  }
   public int getAge() {
       return age;
  }
   public void setAge(int age) {
       this.age = age;
  }
private void privateMethod() {
   System.out.println("private method...");
}
   private void privateMethod2(String name) {
       System.out.println("private method..."+name);
  }

   public static void staticMethod(){}
   @Override
   public void interfaceMethod() {
       System.out.println("interface Method");
  }

   @Override
   public void inteface2Method() {
       System.out.println("interface2 Method");
  }
}
package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectDemo01
{
   //通过反射获取类
   public static void demo01()
  {
       //获取反射对象(反射入口):Class, 1 Class.foName(全类名(包加类名)) 2.XX.class 3.对象.getClass()
       try {
           //1.Class.forName(全类名)
           Class perClazz= Class.forName("reflect.Person");
           System.out.println(perClazz);
           /*
           拿到了类
           class reflect.Person
            */
      } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
      }
       //2.类名.class
       Class perClaszz2=Person.class;
       System.out.println(perClaszz2);
       //3.对象.getClass()
       Person per=new Person();
       Class perClazz3=per.getClass();
       System.out.println(perClazz3);
  }

//获取公共方法
   public static void demo02(){
       //Class入口
       Class perClazz=null;
       try {
            perClazz=Class.forName("reflect.Person");
      } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
      }
       //获取所有的公共的方法(1.本类以及父类,接口中的所有方法 2.符合访问修饰符规律)
       Method[] methods = perClazz.getMethods();
       for (Method method:methods){
           System.out.println(method);
      }
       System.out.println("=============");
       //获取当前类的所有方法(1.只能是当前类 2.忽略访问修饰符限制)
       Method[] declaredMethods = perClazz.getDeclaredMethods();
       for (Method method:declaredMethods){
           System.out.println(method);
      }
  }

   //获取所有接口
   public static void demo03(){
       Class perClazz=null;
       try {
           perClazz=Class.forName("reflect.Person");
      } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
      }
       Class[] interfaces = perClazz.getInterfaces();
       for (Class intere:interfaces)
      {
           System.out.println(intere);
      }
  }

   //获取所有父类
   public static void demo04() {
       Class perClazz = null;
       try {
           perClazz = Class.forName("reflect.Person");
      } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
      }
       //因为父类有一个,单继承,多实现
       Class superclass = perClazz.getSuperclass();
       System.out.println(superclass);
  }

   //获取所有的构造方法
   public static void demo05() {
       Class perClazz = null;
       try {
           perClazz = Class.forName("reflect.Person");
      } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
      }
       Constructor[] constructors = perClazz.getConstructors();
       for (Constructor constructor : constructors) {
           System.out.println(constructor);
      }
  }
       //获取所有的公共属性
       public static void demo06() {
           Class perClazz = null;
           try {
               perClazz = Class.forName("reflect.Person");
          } catch (ClassNotFoundException e) {
               throw new RuntimeException(e);
          }
           //公共属性
           Field[] fields = perClazz.getFields();
           for (Field field:fields)
          {
               System.out.println(field);
          }
           //所有属性
           Field[] declaredFields = perClazz.getDeclaredFields();
           for (Field field:declaredFields)
          {
               System.out.println(field);
          }
      }

       //获取当前反射所代表类(接口)的对象(实例)
   public static void demo07() throws Exception {
       Class perClazz = null;
       try {
           perClazz = Class.forName("reflect.Person");
      } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
      }
       Object instance = perClazz.newInstance();
       //为了证明是Person类;强转Person,调用一个方法实验,证明instance确实是Person类型的
       Person per=(Person) instance;
       per.inteface2Method();
//per对象就是Person
  }
   
   public static void main(String[] args)
  {
//       demo01();
       demo02();
 //     demo03();
     // demo04();
     // demo05();
       demo06();
  }
}
package reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo02
{
   //获取对象的实例,并操作对象
   public static void demo01() throws Exception {
       Class perClazz=null;
       try {
           perClazz=Class.forName("reflect.Person");
      }catch (Exception e){
           e.printStackTrace();
      }
       //通过对象来操作
       Person per=(Person)perClazz.newInstance();
       per.setName("zs");
       per.setAge(24);
       System.out.println(per.getName()+""+per.getAge());
}

   public static void demo02() throws Exception {
       Class perClazz = null;
       try {
           perClazz = Class.forName("reflect.Person");
      } catch (Exception e) {
           e.printStackTrace();
      }
       //操作属性
       //先拿到对象,在通过对象操作属性
       Person per=(Person)perClazz.newInstance();
       Field id = perClazz.getDeclaredField("id");//传什么拿什么(写什么就拿到什么)
       //访问的是private修饰的id,但是private是私有
       //修改属性访问权限 使用反射时,如果因为访问修饰符限制造成异常,可以通过 Field/Method/ Constructor.setAccessible(true)
       id.setAccessible(true);
       id.set(per,1); //相当于per.setId(1); 但并不是它
       System.out.println(per.getId());

       System.out.println("================");
       
   //操作方法
       //无惨
       Method privateMethod = perClazz.getDeclaredMethod("privateMethod", null);
      privateMethod.setAccessible(true);
       privateMethod.invoke(per,null); //方法调用:invoke(); 以前调方法per.say(xxx);
       
        //有参
       Method privateMethod2 = perClazz.getDeclaredMethod("privateMethod2", String.class);//String.class 反射入口
       privateMethod2.setAccessible(true);
       privateMethod2.invoke(per,"zs");
  }
   
   //动态加载类名 和方法
   public static void demo04() throws Exception {
       Properties prop=new Properties();//属性文件,通过这个把属性名字引进来
       prop.load(new FileReader("class.txt"));
       String classname=prop.getProperty("classname"); //类
       String methodname = prop.getProperty("methodname"); //方法
       Class perClazz = null;
       try {
           perClazz = Class.forName("classname"); //文件写的谁就加载谁

      } catch (Exception e) {
           e.printStackTrace();
      }
       //调方法
       Method method = perClazz.getMethod(methodname);
       method.invoke(perClazz.newInstance()); //对象(对象是通过反射拿到的)点方法
  }

   //反射可以越过泛型检查(等后面在回来学)
public static void demo05(){

}
   
   public static void main(String[] args) throws Exception {
       // demo01();
        demo02();
  }
}
//创建一个文件:动态加载
classname=reflect.Person (包.类地址)
methodname=staticMethod
 
posted @ 2022-10-03 17:51  zjw_rp  阅读(68)  评论(0)    收藏  举报