Java反射:创建一个实现类

Java反射:创建一个实现类

问题描述:

Class someInterface = Class.fromName("some.package.SomeInterface");

我现在如何创建一个实现 someInterface的新类

How do I now create a new class that implements someInterface?

我需要创建一个新类,并将其传递给需要 SomeInterface 的函数作为一个参数。

I need to create a new class, and pass it to a function that needs a SomeInterface as an argument.

创建一些假装即时实现接口的东西实际上并不太难。您可以使用 java。执行 rel =noreferrer> InvocationHandler 处理任何方法调用。

Creating something which pretends to implement an interface on the fly actually isn't too hard. You can use java.lang.reflect.Proxy after implementing InvocationHandler to handle any method calls.

当然,你实际上可以使用像 BCEL 这样的库生成一个真正的类。

Of course, you could actually generate a real class with a library like BCEL.

如果这是出于测试目的,你应该看看像 jMock EasyMock

If this is for test purposes, you should look at mocking frameworks like jMock and EasyMock.