我正在尝试使用Class.forName,但我的Intellij会抛出编译错误。我的IntelliJ在testMethod中将“theResponse”用红色标记,并给出以下错误:
cannot find symbol symbol : method
这里是我正在处理的代码(和测试)...
package http.response;
public class TestClass {
public TestClass() {
PublicRoute publicRoute = new PublicRoute();
}
public String testMethod() throws ClassNotFoundException {
Class c = Class.forName("http.response.PublicRoute");
return c.theResponse("hi");
}
}
package http.response;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class TestClassTest {
@Test
public void test() throws ClassNotFoundException {
TestClass testClass = new TestClass();
assertEquals("public", testClass.testMethod());
}
}
更新: 我想要做的是从哈希表返回的类 作为字符串 “多态地”调用 theResponse。我应该怎么做呢?我(宽泛地)遵循这个示例,但我并没有完全理解它 (http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)。这是我尝试做的简化版本。希望这样能让人理解。
package http.response;
import java.util.HashMap;
public class TestClass {
HashMap map;
public TestClass(HashMap map) {
this.map = map;
}
public String testMethod(String lookupValue) throws ClassNotFoundException {
String className = map.get(lookupValue);
Class c = Class.forName("http.response." + className);
return c.theResponse();
}
}