问题描述
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.lang.reflect.Proxy
实施后 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.
这篇关于Java 反射:创建一个实现类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!