如何动态创建实现某些接口的新类并实例化它? [英] How to dynamically create new class implementing some interface and instantiate it?

查看:79
本文介绍了如何动态创建实现某些接口的新类并实例化它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时用Java编写新的类?

Is it possible to compose new class at runtime in Java?

这意味着什么?便餐?编译器API?

What are the means for that? Refection? Compiler API?

我能做

package tests;

public class TryReflection02 {

    interface A {

    }

    public static void main(String[] args) {

        Object o = new A() {};

        System.out.println( o.toString() );

        o = A.class.newInstance() // exception

    }

}

我可以做具有 A.class 值的东西吗?

Can I do the same having A.class value?

推荐答案

不,您不能. A 是一个接口,只能实例化类.

No, you can't. A is an interface, and only classes can be instantiated.

您可以 做的是使用一个使用一些技巧的库/帮助程序来创建一个实现接口并实例化那个的类.JDK的 Proxy 类包含用于执行此操作的静态方法.对于与测试相关的用例,还有一些可以定制的工具可以做到: mockito ,例如.

What you can do is to use a library/helper that uses some trickery to create a class that implements the interface and instantiates that. The JDK's Proxy class contains static methods to do just that. There are also tools that can do it which are custom-geared for test-related use cases: mockito, for instance.

这些工具的作用恰恰是您在该问题的标题中所暗示的内容:它们不是实例化接口,而是生成一个实现该接口的新类,然后实例化该类.

These tools do exactly what you hint at in this question's title: rather than instantiating the interface, they generate a new class that implements the interface, and then instantiate that class.

这篇关于如何动态创建实现某些接口的新类并实例化它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆