有没有办法做到以下几点?检查一个类是否存在(在同一包中),如果确实存在,则检查一个特定的方法是否存在,如果存在,则调用它?
假设我有X类。在X类的某种方法中,我想执行以下操作:
if (class Y exists) { //Maybe use Class.forName("Y")?
if ( Y has method a(String, String) ) {
call Y.a("hello", "world");
}
}
这样的事情可能吗?这样做是合理的吗?谢谢。
最佳答案
这样的事情可能吗?这样做是合理的吗?
谢谢。
当然可以。
如果您开发必须动态发现某些类的程序或库,这是非常合理的事情。
如果不是这种情况,那就不可能。
如果您的需要是合理的,那么您应该问另一个问题:您应该调用静态方法还是实例方法?
这是两种解决方案的示例示例: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和hello的实例方法
5和你好的静态方法