繁体   English   中英

使用类名从不同的类调用方法

[英]Calling methods from different classes with the class name

我有单例模式的各种课程。 它们都是从抽象类扩展而来的。 每个类都有一个getInstance()方法(名称完全相同)。 我想获取具有类名称(字符串)的实例。 例如

public abstract class AbsCls {
}

public class A extends AbsCls {
  private static A a;
  private A() {
}
public synchronized static A getInstance() {
  if(a==null) {
    a == new A();
  }
  return a;
}

public class Test {
  public static void main(String[] args) {
    AbsCls[] array = new AbsCls[5];
    array[0]=neededFunction("A");
    array[1]=neededFunction("B");
  }
}

所有类都与类A具有相同的结构。needFunction()应该如何?

我可以写“ if .. else”,但是我觉得应该有一个更优雅的方法。 感谢您的任何提前帮助...

您可以在package.ClassName ,Reflection和Class.forName(theName)使用完整的类名。

例如,使用String对象:

try {
    String newString = (String)Class.forName("java.lang.String").newInstance();
}
catch (IllegalAccessException iae) {
    // TODO handle
}
catch (InstantiationException ie) {
    // TODO handle
}
catch (ClassNotFoundException cnfe) {
    // TODO handle
}

因此,您的方法大致如下所示:

@SuppressWarnings("unchecked")
public static <T> T getInstance(String clazz) {
    // TODO check for clazz null
    try {
        return (T)Class.forName(clazz).getMethod("getInstance", (Class<?>[])null).invoke(null, (Object[])null);
    }
    catch (ClassNotFoundException cnfe) {
        // TODO handle
        return null;
    }
    catch (NoSuchMethodException nsme) {
        // TODO handle
        return null;
    }
    catch (InvocationTargetException ite) {
        // TODO handle
        return null;
    }
    catch (IllegalAccessException iae) {
        // TODO handle
        return null;
    }
}

编辑 OP:

(Class<?>[])null(Object[])null是转换为预期类型的null参数。

基本上:

  • ClassgetMethod方法采用一个String表示该方法的名称,并使用Class<?>的varargs表示其参数类型。 我们调用的方法( getInstance )不带参数,因此getMethod的参数为null,但我们希望将其getMethod为期望的参数。 更多信息在这里
  • Methodinvoke方法以Object为目标实例来调用该方法(在本例中为null因为它是一个类方法),而Object的varargs作为参数。 但是同样,您的getInstance方法不接受任何参数,因此我们使用null并将其强制转换为Object数组。 更多信息在这里
AbsCls[] array = new AbsCls[5]; // this create object for AbsCls
 array[0]=neededFunction("A"); // calling method from AbsCls
array[1]=neededFunction("B");// calling method from AbsCls

如果为超类创建对象,则无法从子类获取方法

 AbsCls[] array = new A[5]; //this create object for A

如果要调用超类方法用户super关键字,则可以访问这两个类

    array[0]=neededFunction("A"); //// calling method from A
    array[1]=super.neededFunction("B");//// calling method from AbsCls

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM