Solved

Traverse Members of a java class

Posted on 2004-09-07
14
299 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
 
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now