是這樣的薄g可能嗎?這樣做是否合理? 謝謝。
當然這是可能的。
如果您開發一個程序或庫,必須動態地發現一些類,這是一個非常合理的事情。
如果不是這種情況,那不可能。
如果您的需要合理,您應該問您一個額外的問題:您是否應該調用靜態方法或實例方法?
下面是兩種溶液的樣品例如:
ReflectionClass
包含邏輯使用反射:
import java.lang.reflect.Method;
public class ReflectionCalls {
public static void main(String[] args) {
new ReflectionCalls();
}
public ReflectionCalls() {
callMethod(true);
callMethod(false);
}
private void callMethod(boolean isInstanceMethod) {
String className = "DiscoveredClass";
String staticMethodName = "methodStatic";
String instanceMethodName = "methodInstance";
Class<?>[] formalParameters = { int.class, String.class };
Object[] effectiveParameters = new Object[] { 5, "hello" };
String packageName = getClass().getPackage().getName();
try {
Class<?> clazz = Class.forName(packageName + "." + className);
if (!isInstanceMethod) {
Method method = clazz.getMethod(staticMethodName, formalParameters);
method.invoke(null, effectiveParameters);
}
else {
Method method = clazz.getMethod(instanceMethodName, formalParameters);
Object newInstance = clazz.newInstance();
method.invoke(newInstance, effectiveParameters);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DiscoveredClass
(我們在示例操作類)
package reflectionexp;
public class DiscoveredClass {
public static void methodStatic(int x, String string) {
System.out.println("static method with " + x + " and " + string);
}
public void methodInstance(int x, String string) {
System.out.println("instance method with " + x + " and " + string);
}
}
輸出:
實例方法有5個招呼
與5靜態方法和Hello
無論是合理取決於您的要求。在大多數情況下,這是不合理的。在極少數情況下,它*是合理的,你很可能明白你在做什麼以及你爲什麼這樣做。 – Kayaman