Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Traverse Members of a java class

Posted on 2004-09-07
14
Medium Priority
?
315 Views
Last Modified: 2006-11-17
Is it possible to generically traverse through a list members in  a class and store their values in a string

eg

Class test
{
         String  a = " hello ";
         String  b = "world ";
}

The solution would be a function called test.writemem which would traverse through the members and return "Hello world"  without calling the members by name.(saying String = a + b;)

0
Comment
Question by:seanfurlong
  • 5
  • 5
  • 3
  • +1
14 Comments
 
LVL 18

Accepted Solution

by:
armoghan earned 1000 total points
ID: 12003494
Yes you can use reflection for it
0
 
LVL 92

Expert Comment

by:objects
ID: 12003499
Use reflection

Class c = test.class;
Field[] fileds = c.getDeclaredFields();

the order is indeterminate though.
0
 
LVL 18

Expert Comment

by:armoghan
ID: 12003503
public class Test2 {
  public static void main(String args[])
    throws Exception {
    Field f;
   
    f = test .class.getField("a");
    System.out.println("" + f);

    f = test .class.getField("b");
    System.out.println(""+ f);
  }
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 18

Expert Comment

by:armoghan
ID: 12003506
0
 
LVL 18

Expert Comment

by:armoghan
ID: 12003547
This piece of code works

final Field fields[] =
   final Field fields[] =     test .class.getDeclaredFields();
    for (int i = 0; i < fields.length; ++i) {
   
        test fieldTest = new test ();
        Field f = fields[i];
        f.setAccessible(true);
        try {
          System.out.println(f.get(fieldTest));
        }
        catch (IllegalAccessException ex) {
        }
        catch (IllegalArgumentException ex) {
        }
    }
0
 

Expert Comment

by:Emilda
ID: 12004224
Try this:

import java.lang.reflect.Field;

public class TestFields {
   String  a = " hello ";
   String  b = "world ";

  public static void main(String[] args) {
    TestFields test = new TestFields();
    try {
           String values = test.writemem();              
           System.out.println(values);
    } catch (IllegalAccessException e) {
    }
  }
  public String writemem() throws IllegalAccessException {
    Field[] fields = TestFields.class.getDeclaredFields();
    String values = new String();
          
    for(int i=0; i<fields.length; i++) {                
          String name =  fields[i].getName();
          if(name.indexOf("class") == -1) {
             String value = fields[i].get(this).toString();
             values = values + value;
          }                
    }
    return values;
  }
}

0
 
LVL 1

Expert Comment

by:softengg
ID: 12004621
This program will print the fields as u have asked. Output of the following programs on console is "hello world  under world"

package untitled1;

import java.lang.reflect.*;
import java.awt.*;

public class Untitled1 {
  public String a = "hello";
  public String b = "world";
  public String c = " under world";
  public Untitled1() {
  }

  public static void main(String[] args) {
    Untitled1 u = new Untitled1();
    Rectangle r = new Rectangle(100, 325);
    u.me(u.getClass());
  }

  void me(Class c) {
    Field heightField;
    Field field;
    Integer heightValue;
    StringBuffer buf = new StringBuffer();
    try {
      Field[] publicFields = c.getFields();
      for (int i = 0; i < publicFields.length; i++) {
        field = publicFields[i];
        String fieldName = publicFields[i].getName();
        String value = (String) field.get(this);
        buf.append(value);
        buf.append(" ");
      }
    }
    catch (SecurityException e) {
      System.out.println(e);
    }
    catch (IllegalAccessException e) {
      System.out.println(e);
    }
    System.out.println(buf.toString());

  }

}
0
 

Expert Comment

by:Emilda
ID: 12012331
getFields() returns only the public fields.
0
 
LVL 1

Expert Comment

by:softengg
ID: 12013606
The requiremnt is not to list private fields.
0
 

Expert Comment

by:Emilda
ID: 12013629
See the class given in the question. The fields given inside that doesn't have the public identifier.
0
 
LVL 1

Expert Comment

by:softengg
ID: 12014598
Here is the modified code: this will print all variables, public, private, and package level in a class.


package untitled1;

import java.lang.reflect.*;
import java.awt.*;

public class Untitled1 {
  public String a = "hello";
  public String b = "world";
  private String c = " under world";
  public Untitled1() {
  }

  public static void main(String[] args) {
    Untitled1 u = new Untitled1();
    Rectangle r = new Rectangle(100, 325);
    u.me(u.getClass());
  }

  void me(Class c) {
    Field heightField;
    Field field;
    Integer heightValue;
    StringBuffer buf = new StringBuffer();
    try {
      Field[] publicFields = c.getDeclaredFields();
      for (int i = 0; i < publicFields.length; i++) {
        field = publicFields[i];
        String fieldName = publicFields[i].getName();
        String value = (String) field.get(this);
        buf.append(value);
        buf.append(" ");
      }
    }
    catch (SecurityException e) {
      System.out.println(e);
    }
    catch (IllegalAccessException e) {
      System.out.println(e);
    }
    System.out.println(buf.toString());

  }

}
0
 
LVL 1

Expert Comment

by:softengg
ID: 12014603
The last code posted by me will print this our put.

hello world  under world

U can verify this.
0
 
LVL 1

Expert Comment

by:softengg
ID: 12023972
Dear seanfurlong, COnfirm me that the code pasted by me is working or not. I have tested and it is printing all the members of the class i.e. private, public and package level with their values.
0
 
LVL 18

Expert Comment

by:armoghan
ID: 12186721
thanx :)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

876 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question