JAVA 反射应用

JAVA 反射的应用

参考链接:

Java高级特性——反射
Java反射技术详解

前言

我们知道,JAVA类的使用需要JVM提前将类加载到内存中,之后才能使用。有时服务器突然需要用到某个类,但是我们的代码却没有将这个类加载到内存中,无法生成对应的对象,有没有办法根据服务器需要的类的名字动态地生成对象呢?有!JAVA的反射机制给我们提供了实现这种方法的可能性。目前spring等许多框架的底层原理都与java反射有着许多联系。

首先介绍java反射的基本方法,以后有时间再加上一个小例子来简单演示一下反射的应用。

一、最基本的反射技术

  1. 通过class.forName(),传入类名字符串得到一个类

  2. 通过获得的类生成一个对象

    package blog;
    
    /*
     * Student 类
     */
    public class Student{
    	String name;
    	int id;
    	public Student() {} 
    	public Student(String name, int id) {
    		this.id = id;
    		this.name = name;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	@Override
    	public String toString() {
    		return "Student [name=" + name + ", id=" + id + "]";
    	}
        
        private void method_1(String param) {
    		System.out.println("这里是私有方法,参数是:"+ param);
    	}
    }
    
    package blog;
    
    public class Main {
        public static void main(String[] args) {
        	String className = "blog.Student";//类名前一定要加上包,否则无法识别
        	try {
    			Class<?> classP = Class.forName(className);//获得Student类
    			Student student = (Student)classP.newInstance();//生成的student对象
    			student.setId(1);
    			student.setName("xsy");
    			System.out.println("生成的Student的对象:"+student.toString());//打印student对象
    			
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		}
        }  
    }
    

    运行结果:

    生成的Student的对象:Student [name=xsy, id=1]

二、通过反射获取类的成员

  1. 获取类的构造函数,然后通过构造函数生成对象

    注意,**getDeclaredConstructor()是获取类的所有构造函数(包括私有的),而getConstructor()**获取的是类的所有公有的构造函数。

    package blog;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    
    public class Main {
        public static void main(String[] args) {
        	String className = "blog.Student";//类名前一定要加上包,否则无法识别
        	try {
        		//获得Student类
    			Class<?> classP = Class.forName(className);
    			//获取类的构造函数Student(name,id,若无此方法,则会NoSuchMethodException
    			Constructor<?> constructor = classP.getDeclaredConstructor(String.class, int.class);
    			//通过构造函数生成对象
    			Student student = (Student)constructor.newInstance("theory",2);
    			//打印对象
    			System.out.println(student);
    			
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (NoSuchMethodException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		}
        	
        }  
    }
    

    运行结果:

    Student [name=theory, id=2]

  2. 获取类的私有属性

    注意,**getDeclaredField()是获取类的所有变量(包括私有的),而getField()**获取的是类的所有公有的变量。

    package blog;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    
    public class Main {
        public static void main(String[] args) {
        	String className = "blog.Student";//类名前一定要加上包,否则无法识别
        	try {
        		//生成Student对象
        		Class<?> classP = Class.forName(className);
    			Constructor<?> constructor = classP.getConstructor(String.class,int.class);
    			Student student = (Student)constructor.newInstance("衍射", 3);
    			//获取student的私有属性和值
    			Field field = classP.getDeclaredField("name");
    			field.setAccessible(true);
    			String name = (String) field.get(student);
    			//打印私有属性的值
    			System.out.println("对象的私有属性name:"+name);
    			
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (NoSuchMethodException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		} catch (NoSuchFieldException e) {
    			e.printStackTrace();
    		}
        	
        }  
    }
    

    对象的私有属性name:衍射

  3. 获取类的私有方法,并调用此方法

    注意,**getDeclaredMethod()是获取类的所有方法(包括私有的),而getMethod()**获取的是类的所有公有的方法。

    //上方Student的私有方法如下
    private void method_1(String param) {
    	System.out.println("这里是私有方法,参数是:"+ param);
    }
    
    package blog;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class Main {
        public static void main(String[] args) {
        	String className = "blog.Student";//类名前一定要加上包,否则无法识别
        	try {
        		//生成Student对象
        		Class<?> classP = Class.forName(className);
    			Constructor<?> constructor = classP.getConstructor();
    			Student student = (Student)constructor.newInstance();
    			//获取student的私有方法
    			Method method = classP.getDeclaredMethod("method_1",String.class);
    			method.setAccessible(true);
    			//调用私有方法
    			Object[] arg1s = {"参数1"};
    			method.invoke(student, arg1s);
    			
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (NoSuchMethodException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		}
        	
        }  
    }
    
原文地址:https://www.cnblogs.com/theory/p/11884324.html