Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huoguang_/article/details/89236376
Reflective mode
package reflect;
/*
* @Title:通过反射构建对象,没有参数的类的反射生成的对象
*/
public class ReflectServiceImpl {
public void sayHello(String name) {
System.err.println("Hello " + name);
}
/*
* @Description:生成对象并返回对象
* @param:无
* @return:ReflectServiceImpl对象
*/
public ReflectServiceImpl getInstance(){
ReflectServiceImpl object = null;
try {
object = (ReflectServiceImpl) Class.forName("reflect.ReflectServiceImpl").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
}
package reflect;
import java.lang.reflect.InvocationTargetException;
/*
* @Title:通过反射构建对象,有参数的类的反射生成的对象
*/
public class ReflectServiceImpl2 {
private String name;
public ReflectServiceImpl2(String name) {
this.name = name;
}
public void sayHello() {
System.err.println("hello " + name);
}
public ReflectServiceImpl2 getInstance() {
ReflectServiceImpl2 object = null;
try {
object = (ReflectServiceImpl2) Class.forName("reflect.ReflectServiceImpl2").getConstructor(String.class).newInstance("张三");
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
}
test
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import reflect.ReflectServiceImpl;
public class ReflectTest {
public static void main(String[] args) {
}
public Object reflect() {
ReflectServiceImpl object = null;
try {
//通过反射生成对象
object = (ReflectServiceImpl) Class.forName("reflect.ReflectServiceImpl").newInstance();
//获得反射的方法对象
Method method = object.getClass().getMethod("sayHello", String.class);
//反射方法
method.invoke(object, "张三");
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
ex.printStackTrace();
}
return object;
}
}