Solved

Traverse Members of a java class

Posted on 2004-09-07
14
311 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 3
  • +1
14 Comments
 
LVL 18

Accepted Solution

by:
armoghan earned 500 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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

627 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