JDK高级使用--反射

//创建对象

Class c1=student.getClass;
Class c2=Student.class;
Class c3=Class.forName(“com.xxx.demo.Student”);

//获取构造方法并使用

public Constructor[] getConstructors();//所有"公有的"构造方法 
public Constructor[] getDeclaredConstructors();//获取所有的构造方法(包括私有、受保护、默认、公有) 
public Constructor getConstructor(Class... parameterTypes);//获取单个的"公有的"构造方法
public Constructor getDeclaredConstructor(Class... parameterTypes);//获取"某个构造方法"可以是私有的,或受保护、默认、公有
Constructor-->newInstance(Object... initargs) ;//调用构造方法

//获取成员变量并调用

Field[] getFields();//获取所有的"公有字段" 
Field[] getDeclaredFields();//获取所有字段,包括:私有、受保护、默认、公有
public Field getField(String fieldName);//获取某个"公有的"字段
public Field getDeclaredField(String fieldName);//获取某个字段(可以是私有的) 
Field --> public void set(Object obj,Object value);//设置字段的值(obj:要设置的字段所在的对象,value:要为字段设置的值

//获取成员方法并调用:

public Method[] getMethods();//获取所有"公有方法"(包含了父类的方法也包含Object类) 
public Method[] getDeclaredMethods();//获取所有的成员方法,包括私有的(不包括继承的) 
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 Demo {  
     public static void main(String[] args) throws Exception {  
         //通过反射获取Class对象  
         Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"  
         //2获取show()方法  
        Method m = stuClass.getMethod(getValue("methodName"));//show  
        //3.调用show()方法  
        m.invoke(stuClass.getConstructor().newInstance());  
    }  
    //此方法接收一个key,在配置文件中获取相应的value  
    public static String getValue(String key) throws IOException{  
        Properties pro = new Properties();//获取配置文件的对象  
        FileReader in = new FileReader("pro.txt");//获取输入流  
        pro.load(in);//将流加载到配置文件对象中  
        in.close();  
        return pro.getProperty(key);//返回根据key获取的value值  
    }  
}

通过反射越过泛型检查。例如:有一个String泛型的集合,怎样能向这个集合中添加一个Integer类型的值?

public class Demo {  
     public static void main(String[] args) throws Exception{  
         ArrayList<String> strList = new ArrayList<>();  
         strList.add("aaa");  
        strList.add("bbb");  
        //strList.add(100);  
        //获取ArrayList的Class对象,反向的调用add()方法,添加数据  
        Class listClass = strList.getClass(); //得到 strList 对象的字节码 对象  
        //获取add()方法  
        Method m = listClass.getMethod("add", Object.class);  
        //调用add()方法  
        m.invoke(strList, 100);  
        //遍历集合  
        for(Object obj : strList){  
            System.out.println(obj);  
        }  
    }  
}

猜你喜欢

转载自blog.csdn.net/qq_31120741/article/details/82193000
今日推荐