我想避免模拟类的getClass()方法,但似乎无法找到它的任何方法.我正在尝试测试一个将HashMap中的对象类类型存储到以后要使用的特定方法的类.一个简短的例子是:
public class ClassToTest {
/** Map that will be populated with objects during constructor */
private Map<Class<?>, Method> map = new HashMap<Class<?>, Method>();
ClassToTest() {
/* Loop through methods in ClassToTest and if they return a boolean and
take in an InterfaceA parameter then add them to map */
}
public void testMethod(InterfaceA obj) {
final Method method = map.get(obj.getClass());
boolean ok;
if (method != null) {
ok = (Boolean) method.invoke(this, obj);
}
if (ok) {
obj.run();
}
} …Run Code Online (Sandbox Code Playgroud)