-4

I have this class:

public class MyClass{
   private Test test;

   public class Test{
     int num;
     String color;

     public Test(int num, String color){
     this.num = num;
     this.color = color;
     }
   }

   public MyClass(){

   }

   public void setNum(int number){
       test.num = number;
   }

   public void setColor(String color){
       test.color = color;
   }

   public Test getTest(){
       return test;
   }
}

I am setting the values from another class and at the end I call the method getTest:

MyClass myclass = new MyClass();
.
.    
.
Test test1 = myclass.getTest();

I want to Iterate the object test1 to get the values. Is that possible? Do I have to implement hasNext() method inside the class MyClass? If yes, how can I do it?

dirac
  • 309
  • 1
  • 9

3 Answers3

0

You question has already been asked and answered.

Basic idea - you need to use reflection API . E.g construction test.getClass().getDeclaredFields();

Note: you will not create iterator this way, but you will be able to iterate through class fields. That slightly different things.

Community
  • 1
  • 1
Dmitry
  • 1,263
  • 11
  • 15
0

You want this?

public static void main(String[] args) {

    MyClass myclass = new MyClass();
    Test test1 = myclass.getTest();
    //you need modify private Test test = new Test(1, "hahs");
    //import java.lang.reflect.Field;
    Field[] fields = test1.getClass().getDeclaredFields();
    for (int j = 0; j < fields.length-1; j++) {
        fields[j].setAccessible(true);
        try {
            System.out.println(fields[j].get(test1));
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //output
    //1
    //hahs
}
Sgmder
  • 9
  • 2
-1

You will have to use reflection in order to iterate through the members of the test class. You will have to import java.lang.reflect.* and call Class.forName("test1) to get a Class object, and call the getDeclaredFields method of the Class object to get an array of Field objects. The Field object has get and set methods that get or set the value of the field.

Arthur Laks
  • 524
  • 4
  • 8