Java 反射机制之基础

1、三种获取class的方式

package com.oliver.demo.reflect;

public class MainClass {
    public static void main(String[] args) {
        Student student = new Student();
        Class stuClass = student.getClass();
        System.out.println(stuClass.getName());

        Class stuClass2 = Student.class;
        System.out.println(stuClass2);
        System.out.println(stuClass == stuClass2);

        try {
            Class stuClass3 = Class.forName("com.oliver.demo.reflect.Student");
            System.out.println(stuClass3);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

2、构造函数

package com.oliver.demo.reflect;


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

public class MainConstructor {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Class.forName("com.oliver.demo.reflect.Student");

        // get all PUBLIC constructors
        Constructor[] conArray = clazz.getConstructors();
        for(Constructor con : conArray){
            System.out.println(con);
        }

        // get all constructors
        conArray = clazz.getDeclaredConstructors();
        for(Constructor con : conArray){
            System.out.println(con);
        }

        System.out.println("*****************获取公有、无参的构造方法*******************************");
        Constructor con = clazz.getConstructor(null);
        System.out.println("con = " + con);
        Object obj = con.newInstance();


        System.out.println("******************获取私有构造方法,并调用*******************************");
        con = clazz.getDeclaredConstructor(char.class);
        System.out.println(con);
        //调用构造方法
        con.setAccessible(true);//暴力访问(忽略掉访问修饰符)
        obj = con.newInstance('男');

    }
}

3、成员变量

package com.oliver.demo.reflect;


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

/*
 * 获取成员变量并调用:
 *
 * 1.批量的
 *      1).Field[] getFields():获取所有的"公有字段"
 *      2).Field[] getDeclaredFields():获取所有字段,包括:私有、受保护、默认、公有;
 * 2.获取单个的:
 *      1).public Field getField(String fieldName):获取某个"公有的"字段;
 *      2).public Field getDeclaredField(String fieldName):获取某个字段(可以是私有的)
 *
 *   设置字段的值:
 *      Field --> public void set(Object obj,Object value):
 *                  参数说明:
 *                  1.obj:要设置的字段所在的对象;
 *                  2.value:要为字段设置的值;
 *
 */
public class MainField {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //1.获取Class对象
        Class stuClass = Class.forName("com.oliver.demo.reflect.Student");
        //2.获取字段
        System.out.println("************获取所有公有的字段********************");
        Field[] fieldArray = stuClass.getFields();
        for(Field f : fieldArray){
            System.out.println(f);
        }
        System.out.println("************获取所有的字段(包括私有、受保护、默认的)********************");
        fieldArray = stuClass.getDeclaredFields();
        for(Field f : fieldArray){
            System.out.println(f);
        }

        Field f = stuClass.getField("name");
        System.out.println(f);
        //获取一个对象
        Object obj = stuClass.getConstructor().newInstance();//产生Student对象--》Student stu = new Student();
        //为字段设置值
        f.set(obj, "刘德华");//为Student对象中的name属性赋值--》stu.name = "刘德华"
        //验证
        Student stu = (Student)obj;
        System.out.println("验证姓名:" + stu.name);


        System.out.println("**************获取私有字段****并调用********************************");
        f = stuClass.getDeclaredField("phoneNum");
        System.out.println(f);
        f.setAccessible(true);//暴力反射,解除私有限定
        f.set(obj, "18888889999");
        System.out.println("验证电话:" + stu);
    }
}

4、成员方法

package com.oliver.demo.reflect;

import java.lang.reflect.Method;

/*
 * 获取成员方法并调用:
 *
 * 1.批量的:
 *      public Method[] getMethods():获取所有"公有方法";(包含了父类的方法也包含Object类)
 *      public Method[] getDeclaredMethods():获取所有的成员方法,包括私有的(不包括继承的)
 * 2.获取单个的:
 *      public Method getMethod(String name,Class<?>... parameterTypes):
 *                  参数:
 *                      name : 方法名;
 *                      Class ... : 形参的Class类型对象
 *      public Method getDeclaredMethod(String name,Class<?>... parameterTypes)
 *
 *   调用方法:
 *      Method --> public Object invoke(Object obj,Object... args):
 *                  参数说明:
 *                  obj : 要调用方法的对象;
 *                  args:调用方式时所传递的实参;

):
*/
public class MainMethod {
    public static void main(String[] args) throws Exception {
        //1.获取Class对象
        Class stuClass = Class.forName("com.oliver.demo.reflect.Student");
        //2.获取所有公有方法
        System.out.println("***************获取所有的”公有“方法*******************");
        stuClass.getMethods();
        Method[] methodArray = stuClass.getMethods();
        for(Method m : methodArray){
            System.out.println(m);
        }

        System.out.println("***************获取所有的方法,包括私有的*******************");
        methodArray = stuClass.getDeclaredMethods();
        for(Method m : methodArray){
            System.out.println(m);
        }

        System.out.println("***************获取公有的show1()方法*******************");
        Method m = stuClass.getMethod("show1", String.class);
        System.out.println(m);
        //实例化一个Student对象
        Object obj = stuClass.getConstructor().newInstance();
        m.invoke(obj, "刘德华");

        System.out.println("***************获取私有的show4()方法******************");
        m = stuClass.getDeclaredMethod("show4", int.class);
        System.out.println(m);
        m.setAccessible(true);//解除私有限定
        Object result = m.invoke(obj, 20);//需要两个参数,一个是要调用的对象(获取有反射),一个是实参
        System.out.println("返回值:" + result);


        System.out.println("***************反射 MAIN 方法******************");
        //2、获取main方法
        Method methodMain = stuClass.getMethod("main", String[].class);//第一个参数:方法名称,第二个参数:方法形参的类型,
        //3、调用main方法
        // methodMain.invoke(null, new String[]{"a","b","c"});
        //第一个参数,对象类型,因为方法是static静态的,所以为null可以,第二个参数是String数组,这里要注意在jdk1.4时是数组,jdk1.5之后是可变参数
        //这里拆的时候将  new String[]{"a","b","c"} 拆成3个对象。。。所以需要将它强转。
        methodMain.invoke(null, (Object)new String[]{"a","b","c"});//方式一
        // methodMain.invoke(null, new Object[]{new String[]{"a","b","c"}});//方式二

    }
}

5、反射的应用

package com.oliver.demo.reflect;

import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

public class MainUsage_1 {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName(getValue("className"));
        Method method = clazz.getMethod(getValue("methodName"), String.class);
        method.invoke(clazz.getConstructor().newInstance(),"12");

    }
    private static String getValue(String key) throws IOException {
        Properties properties = new Properties();
        FileReader fr = new FileReader("E:\\Code\\src\\main\\java\\pro.txt");
        properties.load(fr);
        fr.close();
        return properties.getProperty(key);
    }


}
package com.oliver.demo.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class MainUsage_2 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ArrayList<String> strList = new ArrayList<>();
        strList.add("aaa");
        strList.add("bbb");

        Class listClass = strList.getClass();
        Method method = listClass.getMethod("add", Object.class);
        method.invoke(strList, 100);
        //遍历集合
        for(Object obj : strList){
            System.out.println(obj);
        }

    }
}

6、辅助类Student

package com.oliver.demo.reflect;

public class Student {

    //**********字段*************//
    public String name;
    protected int age;
    char sex;
    private String phoneNum;

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", sex=" + sex
                + ", phoneNum=" + phoneNum + "]";
    }


    Student(String str){
        System.out.println("defalut constructor, str = " + str);
    }

    public Student(){
        System.out.println("No parameter constructor.");
    }

    public Student(char name){
        System.out.println("One parameter constructor, name =" + name );
    }

    public Student(String name1, String name2){
        System.out.println("One parameter constructor, name =" + name1 + "," + name2 );
    }

    protected Student(boolean n){
        System.out.println("Protected constructor.");
    }

    private Student(int age){
        System.out.println("Private constructor.");
    }


    public void show1(String s){
        System.out.println("调用了:公有的,String参数的show1(): s = " + s);
    }
    protected void show2(){
        System.out.println("调用了:受保护的,无参的show2()");
    }
    void show3(){
        System.out.println("调用了:默认的,无参的show3()");
    }
    private String show4(int age){
        System.out.println("调用了,私有的,并且有返回值的,int参数的show4(): age = " + age);
        return "abcd";
    }

    public static void main(String[] args) {
        System.out.println("main方法执行了。。。");
    }

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值