[英]How do I use java reflection to instantiate a class that cannot be imported?
I'm writing JUnit tests to test code in another package which must match a pre-defined specification.我正在编写 JUnit 测试来测试另一个必须匹配预定义规范的包中的代码。 The code under test must contains a nested class which I want to instantiate inside the test package -- it's not possible to import this class because it's nested (and so not visible outside the original package).
被测代码必须包含一个嵌套类,我想在测试包内实例化该类——无法导入此类,因为它是嵌套的(因此在原始包外不可见)。
Eg package structure:例如包结构:
packageA
-> ClassA
-> packageA.ClassA$ClassB
tests
-> ClassATest
I need to test a method in ClassA that takes an instance of ClassB as an argument.我需要测试 ClassA 中的一个方法,该方法将 ClassB 的实例作为参数。
I'm currently using reflection to get from ClassA
(which I can import) to ClassB
[ cls.getDeclaredClasses
].我目前正在使用反射从
ClassA
(我可以导入)到ClassB
[ cls.getDeclaredClasses
]。 I can then get a constructor for ClassB
[ cls.getDeclaredConstructor
] and thus create a new instance of ClassB
using the found constructor [ constructor.newInstance
].然后我可以获得
ClassB
[ cls.getDeclaredConstructor
] 的构造函数,从而使用找到的构造函数 [ constructor.newInstance
] 创建ClassB
的新实例。 This call to constructor.newInstance
returns an Object
.这个对
constructor.newInstance
调用返回一个Object
。
How do I get from the returned Object
type to something of the correct ClassB
type so that I can pass it into the ClassA
method under test?我如何从返回的
Object
类型获得正确的ClassB
类型,以便我可以将它传递给被测试的ClassA
方法?
Firstly It is possible to import a nested class.首先,可以导入嵌套类。 Cannot `import static` static inner class?
不能`import static`静态内部类吗?
This is sounds as a bad design that you are forced to use a reflection for tests.这听起来是一个糟糕的设计,您被迫使用反射进行测试。
Because you have got Object
from reflection and you don't have a type accessible, you should also use reflection again to pass it into the method.因为您从反射获得了
Object
并且您没有可访问的类型,所以您还应该再次使用反射将其传递给方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.