interface Myinterface
{
boolean run();
}
class MyClass implements Myintr
{
boolean run()
{
boolean status=false;
disp();//hard coded
show();//hard coded
这里上面两种方法是硬编码的,我们怎么能不硬编码就调用 } 公共无效 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();
} }
你的问题非常不清楚,但我怀疑你正在寻找这样的东西:
我的界面.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");
}
}
主类.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();
}
}