标签:stat cat name .class tde static prope ret except
type=com.itheima.reflect.LoginServiceImpl func=eat paramType=java.lang.String
package com.itheima.reflect;
public class LoginServiceImpl implements LoginService {
@Override
public void say() {
System.err.println("say无参数");
}
@Override
public void say(String name) {
System.err.println("有参数"+name);
}
@Override
public void eat(String food) {
System.err.println("food"+food);
}
@Override
public String speak(String name) {
return "hello"+name;
}
}
package com.itheima.reflect;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectDemo {
public static void main(String[] args) throws Exception {
// 读取配置文件
Properties pro = new Properties();
pro.load(ReflectDemo.class.getClassLoader().getResourceAsStream("xx.properties"));
String type = pro.getProperty("type");
String fnuc = pro.getProperty("func");
String paramType = pro.getProperty("paramType");
// 获取class
Class<?> forName = Class.forName(type);
Object instance = forName.newInstance();
// 方法
Method method = forName.getMethod(fnuc, Class.forName(paramType));
// 参数
method.invoke(instance, "狗蛋儿");
}
}
package com.itheima.reflect;
import java.lang.reflect.Proxy;
public class ProxyDemo {
/**
* 动态代理
*/
public static void main(String[] args) {
//构造一个动态代理的对象
LoginService log =(LoginService) Proxy.newProxyInstance(LoginService.class.getClassLoader(),
new Class<?>[]{LoginService.class}, new MyInvocationHandler() );
log.eat("三明治");
String speak2 = log.speak("speak");
System.err.println(speak2);
String speak = log.speak("sayha");
System.err.println(speak);
log.say();
}
}
package com.itheima.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//在这里面进行测试
if(method.getName().equals("eat")){
System.err.println("我一点都不喜欢"+args[0]);
}
if (method.getName().equals("speak")) {
String speak = new LoginServiceImpl().speak((String) args[0]);
return speak;
}
if (method.getName().equals("say")) {
if (method.getParameterTypes().length > 0) {
System.out.println("我爱死" + args[0] + "了");
} else {
System.out.println("你调的是say()方法,但是我就打印这句话了");
}
}
return null;
}
}
标签:stat cat name .class tde static prope ret except
原文地址:https://www.cnblogs.com/liushisaonian/p/9690854.html