fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.lang.reflect.Field;
  8. import java.lang.reflect.Method;
  9.  
  10. /* Name of the class has to be "Main" only if the class is public. */
  11. class Ideone
  12. {
  13. public static void main (String[] args) throws java.lang.Exception, java.lang.IllegalArgumentException, java.lang.IllegalAccessException
  14. {
  15.  
  16. Ideone i = new Ideone();
  17. Init test = i.new Init();
  18.  
  19. for(Field f : test.getClass().getFields()) {
  20.  
  21. System.out.println("nombre instancia : " + f.getName());
  22.  
  23. if (f.getType() == Test.class) {
  24.  
  25. Class<?> clazz = Ideone.Test.class;
  26. Method method = clazz.getMethod("getNombre");
  27. Ideone.Test typ = (Ideone.Test)f.get(test);
  28.  
  29. method.invoke(typ);
  30.  
  31. System.out.println("nombre que contiene la variable test : " + typ.getNombre());
  32. }
  33. }
  34. }
  35.  
  36. private class Init{
  37.  
  38. public Test sPedro = new Test("Pedro");
  39. public Test sPablo = new Test("Pablo");
  40.  
  41.  
  42. }
  43. private class Test{
  44.  
  45. String test;
  46.  
  47. public Test(String nombre){
  48. test = nombre;
  49. }
  50. public String getNombre(){
  51. return test;
  52. }
  53. }
  54. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
nombre instancia : sPedro
nombre que contiene la variable test : Pedro
nombre instancia : sPablo
nombre que contiene la variable test : Pablo