测试(使用反射)的最简单方法是什么,给定方法(即java.lang.Method实例)是否具有返回类型,可以安全地转换为List <String>?
请考虑以下代码段:
public static class StringList extends ArrayList<String> {}
public List<String> method1();
public ArrayList<String> method2();
public StringList method3();
Run Code Online (Sandbox Code Playgroud)
所有方法1,2,3都满足要求.为method1测试它很容易(通过getGenericReturnType(),它返回ParameterizedType的实例),但对于方法2和3,它并不那么明显.我想,通过遍历所有getGenericSuperclass()和getGenericInterfaces(),我们可以非常接近,但我没有看到,如何匹配List <E>中的TypeVariable(它发生在超类接口中的某处)与实际type参数(即此E与String匹配的位置).
或者是否有一种完全不同(更容易)的方式,我忽略了?
编辑:对于那些正在研究它的人,这里是method4,它也满足了要求,并显示了一些必须调查的案例:
public interface Parametrized<T extends StringList> {
T method4();
}
Run Code Online (Sandbox Code Playgroud) 由于引入了泛型,因此Class被参数化,因此List.class生成Class <List>.这很清楚.
我无法弄清楚的是如何获得一个自身参数化的类型的实例,即Class <List <String >>.就像在这个片段中:
public class GenTest {
static <T> T instantiate(Class<T> clazz) throws Exception {
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
// Is there a way to avoid waring on the line below
// without using @SuppressWarnings("unchecked")?
// ArrayList.class is Class<ArrayList>, but I would like to
// pass in Class<ArrayList<String>>
ArrayList<String> l = GenTest.instantiate(ArrayList.class);
}
}
Run Code Online (Sandbox Code Playgroud)
我经常遇到这个问题的变化,我仍然不知道,如果我只是错过了什么,或者是否真的没有更好的方法.谢谢你的建议.
当我的单元测试中有一些字段时@Mocked
:
@Mocked
private MyService service;
Run Code Online (Sandbox Code Playgroud)
IDEA(我猜Java也是如此)会产生未使用的警告,因为它从未被赋值(因为它只是由JMockit填充) - 尽管它正在被读取。我想知道避免此警告的正确方法是什么。我可以
@SuppressWarnings("unused")
@Mocked
private MyService service;
Run Code Online (Sandbox Code Playgroud)
但这也会在我实际停止使用该字段时抑制警告(我仍然想要那样)。我也可以做
@Mocked
private MyService service = null;
Run Code Online (Sandbox Code Playgroud)
它修复了“未使用”警告,但我收到了“冗余初始化”警告。我可以通过这样做来避免这种情况
@SuppressWarnings("RedundantFieldInitialization")
@Mocked
private MyService service = null;
Run Code Online (Sandbox Code Playgroud)
但这似乎是太多的警告避免代码,不太好。
那么有没有更好的方法来避免警告,避免过于冗长的代码,并且仍然受益于检测真正未使用的变量(=那些从未读取过的变量)?
IDEA 设置Inspections | Unused declaration
为添加注释,其存在将关闭给定字段的警告,但它也会禁用从未读取的字段的警告,因此对我来说这不是完整的解决方案。