在Java中,是否可以从Class对象创建匿名子类的实例? [英] In Java, can I create an instance of an anonymous subclass from a Class object?

查看:172
本文介绍了在Java中,是否可以从Class对象创建匿名子类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工厂方法,该方法创建要在单元测试中使用的对象.这些对象都源自相同的基类:

I have a factory method that creates objects to be used in unit tests. These objects all derive from the same base class:

public static <T extends BaseEntity> T modMake(Class<T> clazz)
{
    try {
        return clazz.newInstance();
    } catch (InstantiationException e) {
        // Should never happen
        throw new AssertionError(e);
    } catch (IllegalAccessException e) {
        // Should never happen
        throw new AssertionError(e);
    }
}

现在,我想重写该基类中的getter方法,但仅用于测试.我通常会使用一个匿名类来做到这一点,例如(NodeBaseEntity的子类之一):

Now I want to override a getter method from that base class, but just for the tests. I would usually do that with an anonymous class, for example (Node being one of the subtaypes of BaseEntity):

public static Node nodMake()
{
    return new Node() {
        @Override
        public long ixGet() { return 1; }
    };
}

我也可以在函数中使用Class自变量吗?

Can I do that in the function using the Class argument, too?

推荐答案

丢失工厂方法,并使用 EasyMock 实现您描述的行为.

Lose your factory method and use a mocking API like EasyMock to achieve the behavior you describe.

您的代码将最终如下所示:

Your code will then end up something like this:

long returnValue = 12;

Node nodeMock = createMock(Node.class);
expect(nodeMock.ixGet()).andReturn(returnValue);
replay(nodeMock);

//add test code here

verify(nodeMock);

要回答Hanno关于其工作原理的问题:

这取决于您是模拟接口还是类.

It depends on whether your mocking an interface or a class.

接口的情况很简单(在代码方面),它使用了称为动态代理的动态代理,该代理是核心Java的一部分.

The case of the interface is simple (code-wise), it uses what's called a dynamic proxy, which is part of core Java.

对于 class ,它正在执行@Jonathan在他的答案中提到的字节码操作,就在一个不错的API后面.

In the case of the class it's doing the bytecode manipulation that @Jonathan mentions in his answer, just behind a nice API.

以上两种机制均允许拦截方法调用,并且 EasyMock 只是根据您的期望进行响应设置.

Both the above mechanisms allow the method calls to be intercepted and EasyMock simply responds based on the expectations you've setup.

这篇关于在Java中,是否可以从Class对象创建匿名子类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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