日期:2014-05-20 浏览次数:20955 次
import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class T { public static synchronized void main(String[] a) throws Exception { T t = new T(); Method m = t.getClass().getMethod("hasNext"); System.out.print(m.invoke(t)); List<T> list = new ArrayList<T>(); list.add(t); Iterator it = list.iterator(); m = it.getClass().getMethod("hasNext"); System.out.print(m.invoke(it)); } public boolean hasNext() { return true; } }
import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class T { public static synchronized void main(String[] a) throws Exception { T t = new T(); Method m = t.getClass().getMethod("hasNext"); System.out.print(m.invoke(t)); List<T> list = new ArrayList<T>(); list.add(t); Iterator it = list.iterator(); m = it.getClass().getMethod("hasNext"); System.out.print(m.invoke(it)); } public boolean hasNext() { return true; } }
------解决方案--------------------
import java.lang.reflect.Method; public class T { public static void main(String[] args)throws Exception{ T t = new T(); Sam sam = t.getIt(); Method m = sam.getClass().getMethod("f"); System.out.println(sam.getClass()); m.invoke(sam); } private class It implements Sam{ public void f(){ System.out.println("F method"); } } public Sam getIt(){ return new It(); } } public interface Sam{ public void f(); }