Test polymorphism in reflection method invoke
package y11.m04;
import java.lang.reflect.Method;
public class d28t01 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// Test polymorphism in reflection
Object invoker = new Invoker();
Class clazz = invoker.getClass();
Dialer p1 = new Phone("12345");
Phone p2 = new Phone("234567");
CellPhone p3 = new CellPhone("345678");
// cause java.lang.NosuchMethodException
try {
Method m1 = clazz.getDeclaredMethod("use", p1.getClass());
m1.invoke(invoker, p1);
} catch (Exception e) {
e.printStackTrace();
}
try {
Method m2 = clazz.getDeclaredMethod("use", p2.getClass());
m2.invoke(invoker, p1);
} catch (Exception e) {
e.printStackTrace();
}
try {
Method m3 = clazz.getDeclaredMethod("use", p3.getClass());
m3.invoke(invoker, p1);
} catch (Exception e) {
e.printStackTrace();
}
Method[] ms = clazz.getDeclaredMethods();
for (Method m : ms) {
if (m.getName().equals("use")) {
Class[] paramTypes = m.getParameterTypes();
if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(p1.getClass())) {
m.invoke(invoker, p1);
}
}
if (m.getName().equals("use")) {
Class[] paramTypes = m.getParameterTypes();
if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(p2.getClass())) {
m.invoke(invoker, p2);
}
}
if (m.getName().equals("use")) {
Class[] paramTypes = m.getParameterTypes();
if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(p3.getClass())) {
m.invoke(invoker, p3);
}
}
}
}
}
class Invoker {
public void use(Dialer dialer) {
if (dialer != null)
dialer.call();
}
}
interface Dialer {
void call();
}
class Phone implements Dialer {
public String number;
public Phone(String number) {
this.number = number;
}
public void call() {
System.out.printf("Call %s%n", number);
}
}
class CellPhone extends Phone {
public CellPhone(String number) {
super(number);
}
@Override
public void call() {
System.out.printf("Dial %s%n", number);
}
}