class D1{
public void showMessage(){
System.out.println("this is class D1");
}
}class D2{
public void showMessage(){
System.out.println("this is class D2");
}class Test{ public static void getWhichClass(Object o){
//how to do if I want to invoke the method in class D1 or D2
} public static void main(String[] args){
getWhichClass(new D1());
getWhichClass(new D2());
}
}请问,有什么方法可以通过方法getWhichClass方法调用到D1类或者D2类中的方法而不用进行强制转化吗
你是指在这个方法里面填写代码吗?
public static void getWhichClass(Object o){
//how to do if I want to invoke the method in class D1 or D2
new D1().showMessage();//直接实例化没有对象名的调用
D2 d2 = new D2();//实例化一个对象名称d2
d2.showMessage();
}
一般是类进行强制转换,
上面的类要在同一个package下面,不然没有public修饰符,是无法访问的!
class D1{
public void showMessage(){
System.out.println("this is class D1");
}
} class D2{
public void showMessage(){
System.out.println("this is class D2");
}
}public class Test{ public static void getWhichClass(Object o){
//how to do if I want to invoke the method in class D1 or D2
try{
o.getClass().getMethod("showMessage", null).invoke(o, null);
} catch(Exception ex) {
ex.printStackTrace();
}
} public static void main(String[] args){
getWhichClass(new D1());
getWhichClass(new D2());
}
}
o.getClass().getMethod("showMessage", null).invoke(o, null);
你完全可以写在不同的包下 然后在Import下
void showMessage();
}
class D1 implements D{
public void showMessage(){
System.out.println("this is class D1");
}
} class D2 implements D{
public void showMessage(){
System.out.println("this is class D2");
} class Test{ public static void getWhichClass(D d){
d.showMessage();
} public static void main(String[] args){
getWhichClass(new D1());
getWhichClass(new D2());
}
}
The argument of type null should explicitly be cast to Object[] for the invocation of the varargs method invoke(Object,
Object...) from type Method. It could alternatively be cast to Object for a varargs invocation
//how to do if I want to invoke the method in class D1 or D2
((D1)o).showMessage();
}
o.getClass().getMethod("showMessage", new Class[]{}).invoke(o, new Object[]{});