Java反射:使用接口初始化对象,但使用类名的字符串值

Java反射:使用接口初始化对象,但使用类名的字符串值,java,inheritance,reflection,interface,abstraction,Java,Inheritance,Reflection,Interface,Abstraction,假设我有以下设置 接口 public interface TestInterface { public void draw(); } 和两个实现 public class Square implements TestInterface { @Override public void draw() { System.out.println("Square"); } } 及 现在我很容易做到 TestInterface a = new Square(); a.dr

假设我有以下设置

接口

public interface TestInterface {

  public void draw();
}
和两个实现

public class Square implements TestInterface {

  @Override
  public void draw() {
    System.out.println("Square");

  }

}

现在我很容易做到

TestInterface a = new Square();
a.draw();
我正确地得到了
平方
。接下来,我想尝试一下反射

Class<?> clazz = null;
    try {
      clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Constructor<?> constructor = null;
    try {
      constructor = clazz.getConstructor();
    } catch (NoSuchMethodException | SecurityException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    Object instance = null;
    try {
      instance = constructor.newInstance();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
        | InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    Method method = null;
    try {
      method = instance.getClass().getMethod(methodName);
    } catch (NoSuchMethodException | SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    try {
      method.invoke(instance);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

有什么方法可以概括它吗?或者,我上面展示的使用反射的方法是实现类似目标的唯一方法吗?最后,如果我使用抽象类而不是接口,会有什么不同吗?

你必须知道类的全名。仅类的名称不足以将其加载到内存中并通过反射使用它。但是,您可以使用库确定接口的实现

也许此讨论线程可以帮助您:

您需要通过:

@param      className   the fully qualified name of the desired class.
例如,当您有三个名称相同但包不同的类时

--package1
----Test
--package2
----Test
Main
Test
主要是:

public static void main(String[] args) throws UnsupportedEncodingException {

        Class<?> clazz = null;
        try {
            clazz = Class.forName("Test");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
如果我只知道类的名称而不知道包的名称怎么办?所以你需要知道你想要什么级别。因为正如您所知,不同的包和类可以有相同的名称。如果你有这个问题,你需要哪门课

--package1
----Test
--package2
----Test
Main
Test
public static void main(String[] args) throws UnsupportedEncodingException {

        Class<?> clazz = null;
        try {
            clazz = Class.forName("Test");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
    clazz = Class.forName("package1.Test");
    clazz = Class.forName("package2.Test");