Java:检查类是否存在并调用特定方法(如果存在)

Hik*_*est 4 java reflection

有办法做到以下几点吗?检查一个类是否存在(在同一个包中),如果它存在,检查是否存在特定方法,如果存在,则调用它?

假设我有类X.在X类的某些方法中,我想执行以下操作:

if (class Y exists) { //Maybe use Class.forName("Y")?
  if ( Y has method a(String, String) ) {
    call Y.a("hello", "world");
  }
}
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?并且这样做是否合理?谢谢.

dav*_*xxx 5

这样的事情可能吗?并且这样做是否合理?谢谢.

当然有可能.
如果你开发一个必须动态发现某些类的程序或库,这是一个非常合理的事情.
如果不是这样,那就不可能.


如果您的需要有意义,您应该问一个额外的问题:您应该调用静态方法还是实例方法?

以下是两个解决方案的示例示例:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
        }

    }
Run Code Online (Sandbox Code Playgroud)

输出:

带有5和hello的实例方法

静态方法用5和hello