亲宝软件园·资讯

展开

Java 动态生成类和实例, 并注入方法 Java 动态生成类和实例, 并注入方法操作示例

David_Ding 人气:0

本文实例讲述了Java 动态生成类和实例, 并注入方法。分享给大家供大家参考,具体如下:

Java官方支持的, 必须要有接口才行

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
 * @author David Ding
 *
 */
interface IJavaGen {
    int getRandomInt();
    void printClassInfo();
}
abstract class JavaGen implements IJavaGen {
    protected List<String> calledMethods = new LinkedList<>(); // property
    public int getRandomInt() { // Get a random integer
        return new Random().nextInt(10000);
    }
    public abstract void printClassInfo();
}
class JavaGenHandler implements InvocationHandler {
    private JavaGen mTarget;
    public JavaGenHandler(JavaGen javaGen) {
        mTarget = javaGen;
    }
    // 动态注入
    @Override
    public Object invoke(Object obj, Method method, Object[] params) throws Throwable {
        Object ret = null;
        String name = method.getName();
        if (name.equals("getRandomInt")) { // intercept the getRandomInt
            ret = method.invoke(mTarget, params); // call the base method
            System.out.println("Print random int: " + ret);
        } else if (name.equals("printClassInfo")) { // print class info
            System.out.println("Class: " + obj.getClass());
            method.invoke(mTarget, params);
        }
        mTarget.calledMethods.add(name); // change the property
        return ret;
    }
}
public class JavaCodeGen {
    public static void main(String[] args) {
        try {
            Class<?> genClass = Proxy.getProxyClass(IJavaGen.class.getClassLoader(), IJavaGen.class);
            Constructor<?> cons = genClass.getConstructor(InvocationHandler.class);
            JavaGen target = new JavaGen() {
                @Override
                public void printClassInfo() {
                    System.out.println("I have to implement this method!!");
                }
            };
            IJavaGen javaGen = (IJavaGen) cons.newInstance(new JavaGenHandler(target));
            javaGen.getRandomInt();
            javaGen.printClassInfo();
            System.out.println(target.calledMethods);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果:

Print random int: 8143
Class: class demo.$Proxy0
I have to implement this method!!
[getRandomInt, printClassInfo]

希望本文所述对大家java程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论