一、通过反射生成无参对象,通过反射调用有参方法
package com.ss.learn.chapter2;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectServiceImpl {
public void sayHello(String name) {
System.out.println("Hello" + name);
}
public static void main(String[] args) {
ReflectServiceImpl object = null;
Method method;
try {
object = (ReflectServiceImpl) Class.forName("com.ss.learn.chapter2.ReflectServiceImpl").newInstance();
method = object.getClass().getMethod("sayHello", String.class);
method.invoke(object, "张三");
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException
| SecurityException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
二、通过反射生成有参对象,通过反射调用无参函数
package com.ss.learn.chapter2;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectServiceImpl2 {
private String name;
public ReflectServiceImpl2(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("Hello" + name);
}
public static void main(String[] args) {
ReflectServiceImpl2 object = null;
try {
object = (ReflectServiceImpl2) Class.forName("com.ss.learn.chapter2.ReflectServiceImpl2").getConstructor(String.class).newInstance("张三");
Method method = object.getClass().getDeclaredMethod("sayHello");
method.invoke(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
三、拓展相关知识
用到的几个API:
.getConstructor(形参类.class , ....)
.getMethod(方法名, 形参.class)
.getDeclareMethod()
.invoke(实例, 参数) // 参数是对象没有的
/invoke(实例) // 实例里已经有实参
反射生成对象的时候
可以用变量Class<?> cls = Class.forName(类的全限定名)来保存类。
Class<?> cls = Class.forName("com.ss.learn.chapter2.ReflectServiceImpl2");
object = (ReflectServiceImpl2) cls.getConstructor(String.class).newInstance("张三");
Method method = cls.getDeclaredMethod("sayHello");
method.invoke(object);
Class.forName(类的全限定名) 等价于 这个类的对象.getClass() 等价于 类名.class
说白了,就是这个“类”的Class实例