fork download
  1. import java.lang.reflect.Field;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. One one = new One();
  9. Class<?> clazz = one.getClass();
  10. try {
  11. Field twoField = clazz.getField("two");
  12. twoField.setAccessible(true);
  13. Class<?> twoClazz =Class.forName(twoField.getType().getName());
  14.  
  15. Method method = twoClazz.getMethod("hello", null);
  16.  
  17. method.invoke(twoClazz.newInstance(), null);
  18. e.printStackTrace();
  19. }
  20. }
  21.  
  22.  
  23. public static class One {
  24. public Two two = new Two();
  25. }
  26.  
  27. public static class Two {
  28. public void hello(){
  29. System.out.println("hello");
  30. }
  31. }
  32. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
hello