代码改变世界

初学反射

2018-10-17 16:07  人月神话。  阅读(138)  评论(0)    收藏  举报
package Reflect;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@SuppressWarnings("unused")
public class Test01 {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
    /*    BufferedReader br = new BufferedReader(new FileReader("config.properties"));
        Class  clazz = Class.forName(br.readLine());
        Fruit f = (Fruit) clazz.newInstance();
        f.squezze(); */
        
        Class clazz = Class.forName("Reflect.Person");
        Constructor  con = clazz.getConstructor(String.class,int.class,double.class);
        Person p = (Person) con.newInstance("张三",18,180);
        System.out.println(p);
        /**
         *    暴力 反射获取私有的构造
         */
        /*Class clazz = Class.forName("Reflect.Person");
        Constructor c0= clazz.getDeclaredConstructor();
        c0.setAccessible(true);//设置私有的可以访问
        Person p = (Person) c0.newInstance();
        System.out.println(p);*/
        
        /**
         * 反射获取字段
         */
    /*    Field f =clazz.getDeclaredField("name");//暴力反射获取字段
        f.setAccessible(true);//设置私有可以访问
        f.set(p, "李四");//修改内容
     
        System.out.println(p);*/
        
        /**
         * 反射获取方法
         */
        Method m1 =clazz.getMethod("eat");
        m1.invoke(p);//最基础的调用
        Method m2 =clazz.getMethod("eat",int.class);//获取有参数的方法
        m2.invoke(p,10);//最基础的调用
        
        
        
    }

}