Java反射技术实现代码
ReflectServiceImpl.java
package com.smmr.chapter2.reflect;
/**
* @ClassName ReflectServiceImpl
* @Description TODO
* @author Mukais
* @date 2018年11月12日
*
*/
public class ReflectServiceImpl {
private String name;
public ReflectServiceImpl() {}
public ReflectServiceImpl(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("Hello " + name);
}
public void sayHello(String name) {
System.out.println("Hello " + name);
}
}Test.java
package com.smmr.chapter2.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @ClassName Test
* @Description TODO
* @author Mukais
* @date 2018年11月12日
*
*/
public class Test {
/**
* 无参构造反射
* @return
*/
public ReflectServiceImpl getInstance1() {
ReflectServiceImpl obj = null;
try {
obj = (ReflectServiceImpl)Class.forName("com.smmr.chapter2.reflect.ReflectServiceImpl").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
/**
* 有参构造反射
* @return
*/
public ReflectServiceImpl getInstance2() {
ReflectServiceImpl obj = null;
try {
obj = (ReflectServiceImpl)Class.forName("com.smmr.chapter2.reflect.ReflectServiceImpl").getConstructor(String.class).newInstance("张三");
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
/**
* 反射方法
* @return
*/
public Object reflectMethod() {
Object obj = null;
try {
obj = (ReflectServiceImpl)Class.forName("com.smmr.chapter2.reflect.ReflectServiceImpl").newInstance();
Method method = obj.getClass().getMethod("sayHello", String.class);
method.invoke(obj, "张三");
} catch (InstantiationException | IllegalAccessException |
ClassNotFoundException | NoSuchMethodException | SecurityException |
IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) {
new Test().getInstance1().sayHello("张三");
new Test().getInstance2().sayHello();
new Test().reflectMethod();
}
}运行结果
Hello 张三 Hello 张三 Hello 张三
- 本文固定链接: https://www.coordsoft.com/post/12.html
- 转载请注明: admin 于 生活随想 - zwgu 's world 发表
《本文》有 0 条评论