java笔记:反射的简单使用

此仅为个人笔记,若有不周之处,万望指正,不胜感激。

反射生成对象

反射生成只有无参数构造函数类的对象
代码如下:
public ReflectServiceImpl getInstance() {
		ReflectServiceImpl object = null;
		try {
			object = (ReflectServiceImpl) Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl").newInstance();
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
			ex.printStackTrace();
		}
		return object;
	}

ReflectServiceImpl为一个没有有参构造函数的类,代码如下:

public class ReflectServiceImpl {
	public void sayHello(String name) {
		System.err.println("Hello " + name);
	}
}
反射生成没有有参构造函数类的对象只需两步:
  1. 得到一个被反射类的Class对象,上述代码中使用的是Class.getName("被反射类的全限定名")
  2. 用第一步中得到的Class对象调用newInstance()函数生成对象
反射生成具有有参数构造函数类的对象

代码如下:

public ReflectServiceImpl2 getInstance() {
	    ReflectServiceImpl2 object = null;
	    try {
	        object = 
	            (ReflectServiceImpl2) 
	            Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl2").
	            getConstructor(String.class).newInstance("张三");
	    } catch (ClassNotFoundException | InstantiationException 
	                | IllegalAccessException | NoSuchMethodException 
	                | SecurityException | IllegalArgumentException 
	                | InvocationTargetException ex) {
	            ex.printStackTrace();
	    }
	    return object;
	}

ReflectServiceImpl2为一个没有有参构造函数的类,代码如下:

public class ReflectServiceImpl2 {
	private String name;
	public ReflectServiceImpl2(String name) {
		this.name = name;
	}
	public void sayHello() {
		System.err.println("hello " + name);
	}
}
反射生成没有有参构造函数类的对象只需三步:
  1. 得到一个被反射类的Class对象,上述代码中使用的是Class.getName("被反射类的全限定名")
  2. 用第一步中得到的Class对象调用getConstructor方法得到构造器Constructor,getConstructor(String.class)中String为有参构造函数的参数类型
  3. 用第二步中得到的构造器Constructor调用newInstance()函数生成对象,newInstance("张三")中"张三"为有参构造函数的参数

反射方法

代码如下:
public Object reflectMethod() {
		Object returnObj = null;
		ReflectServiceImpl target = new ReflectServiceImpl();
		try {
			Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
			returnObj = method.invoke(target, "张三");
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException ex) {
			ex.printStackTrace();
		}
		return returnObj;
	}
反射的方法为类ReflectServiceImpl中的方法sayHello(),代码如下:
public class ReflectServiceImpl {
	public void sayHello(String name) {
		System.err.println("Hello " + name);
	}
}

实现反射方法需两步:

  1. 获得被反射方法所属类的Class对象,上述代码中使用的是类名.class的方法获得
  2. 使用getMethod()方法得到Method对象,getMethod()方法第一个参数为被反射方法的方法名,后面的参数都是反射方法所需参数的参数类型
  3. 使用invoke()方法反射调度被反射方法,invoke()方法第一个参数为被反射方法所属类的对象,后面的参数都是反射方法所需参数
经验分享 程序员 微信小程序 职场和发展