代理实例
package test2Package;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyTest {
interface IHello {
void sayHello();
}
static class Hello implements IHello {
@Override
public void sayHello() {
System.out.println("helloWorld");
}
}
static class DynamicProxy implements InvocationHandler {
Object originalObj;
Object bind(Object originalObj) {
this.originalObj = originalObj;
return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(),
originalObj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("welcom");
return method.invoke(originalObj, args);
}
public static void main(String[] args) {
IHello hello = (IHello) new DynamicProxy().bind(new Hello());
hello.sayHello();
}
}
}
反射实例
package test2Package;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectionTest {
public static void main(String[] args) throws Exception{
Class<?> type = Class.forName("java.net.URL");
Constructor<?> construct = type.getConstructor(String.class);
Object instance = construct.newInstance("https://sitepoint.com/java");
Method method = type.getMethod("toExternalForm");
Object methodCallResult = method.invoke(instance);
System.out.println(methodCallResult);
Class<?> human = Class.forName("test2Package.Human");
Object humanIns = human.newInstance();
Class<?> c = String.class;
Method mm = human.getMethod("sayFuck",c);
String m = "hehe";
System.out.println(mm.invoke(humanIns,m));
}
}
//分派实例 上面的也是引用这个实例
package test2Package;
public class Human {
static class people{}
static class man extends people{}
static class woman extends people{}
public void sayHello(people p){
System.out.println("hello people");
}
public void sayHello(man p){
System.out.println("hello man");
}
public void sayHello(woman p){
System.out.println("hello woman");
}
public void sayFuck(String w){
System.out.println("fuck"+w);
}
public static void main(String[] args) {
people p = new Human.man();
people p1 = new woman();
Human h = new Human();
h.sayHello(p);
h.sayHello(p1);
}
}