实例记录

代理实例

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值