Java反射:创建一个实现类 [英] Java Reflection: Create an implementing class

查看:293
本文介绍了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.

这篇关于Java反射:创建一个实现类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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