Java Reflection: Create an implementing class

后端 未结 4 1053
一个人的身影
一个人的身影 2020-11-27 11:17
Class someInterface = Class.fromName(\"some.package.SomeInterface\");

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

4条回答
  •  迷失自我
    2020-11-27 12:04

    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.

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

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

提交回复
热议问题