Solved

Traverse Members of a java class

Posted on 2004-09-07
14
302 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 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 30
tomcat administrtor 12 61
running on tomcat not jboss eap 7.0 3 18
What browser will run Java? 7 65
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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 …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

828 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