如何在没有硬编码的情况下调用run方法中的实现类方法

时间:2016-03-08 06:42:05

标签: java reflection real-time

interface Myinterface
{
boolean run();
}

class MyClass implements Myintr
{
      boolean run()
      {
          boolean status=false;
           disp();//hard coded
           show();//hard coded

以上两种方法都是硬编码的,我们如何在没有硬编码的情况下调用           }           public void disp()           {                  System.out.println(“Hello Person”);           }

      public void show()
      {
               System.out.println("Welcome");
       }

}

class Mainclass
{
public static void main(String args[])
{

   Class aClass=Class.forName("Myclass");
   Object obj=aClass.newInstance();
   Myinterface myinter=(Myinterface)obj.run();

}   }

1 个答案:

答案 0 :(得分:0)

您的问题非常不清楚,但我怀疑您正在寻找类似的内容:

MyInterface.java:

interface MyInterface {
    void run();
}

Impl1.java:

class Impl1 implements MyInterface {
    @Override
    public void run() {
        System.out.println("Hello Person");
    }
}

Impl2.java:

class Impl2 implements MyInterface {
    @Override
    public void run() {
        System.out.println("Welcome");
    }
}

MainClass.java:

class MainClass {
    public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> aClass = Class.forName("com.mypackage.Impl1");
        Object obj = aClass.newInstance();
        MyInterface myinter = (MyInterface)obj;
        myinter.run();
    }
}