Improve company productivity with a Business Account.Sign Up

x
?
Solved

Class parameter list / amount of parameters...is it possible?

Posted on 2006-06-29
15
Medium Priority
?
205 Views
Last Modified: 2011-09-20
Hi all!

My question is about the parameters and their values.

I have a class like this, which prints out the values of the parameters the class has.

public class Test {
      private String parameter1 = "one";
      private String parameter2 = "two";
      private String parameter3 = "three";
      
      public Test() {
      }

      public static void main(String[] args) {
           Test t = new Test();
           System.out.println(t.parameter1);
           System.out.println(t.parameter2);
           System.out.println(t.parameter3);
      }
}


Is it possible to do this same dynamically? I mean, can I print out all the parameter values of the class...and maybe the name of the corresponding attribute as well. In a somehow similar way you can print out the environmental variables
" import java.util.Properties; System.getProperties().list(System.out); "

I was hoping of making a method which prints out all the attribute values of certain object, and maybe the attribute names as well (I don't if the attribute names still exist with their user defined names at the point you have created an object)

Or can I somehow get the amount of parameters a certain class has?
The number of parameters could be used in for-loop.

Thank You!
PS. I'm quite a newbie with Java :)
0
Comment
Question by:jell-o
15 Comments
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17008444
ya using reflection you can do that
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17008459
try using reflection
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17008526
This will print out the field names,
how ever if the fields are private then you should have getters for them to displa the values

            Class clas = cust.getClass() ;
            
            Field [] field = clas.getDeclaredFields() ;
            
            for ( int i = 0 ; i < field.length ; i ++ )
            {
                  System.out.println ( field[i].getName() ) ;
                  System.out.println( field[i].getGenericType()  ) ;
                  
            }
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17008538
if the fields are not private then,

you can get the field values using

returnObjext =   field[i].get ( objectname) ;
0
 

Author Comment

by:jell-o
ID: 17009066
Thank you all for quick answers

This seems to be just the one I was hoping for...however for some reason I can't make it work :/
How would you do "the thing" into the example code I attached at the top.

Thanks again!
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17009525
This method will work for al fields except private fields,

if you want to access private fields then you should have getter for that field and call that method

      public void displayFields ( Object obj) throws IllegalArgumentException, IllegalAccessException
      {
            Field[] field = obj.getClass().getDeclaredFields()  ;
            Method [] method = obj.getClass() .getDeclaredMethods() ;
            
            for ( int i = 0 ; i < field.length ; i ++ )
            {
                  int modifier = field[i].getModifiers() ;
                  if ( modifier != Modifier .PRIVATE )
                  {
                        Object f = field[i].get( obj ) ;
                        System.out.println ( field[i].getName() + " -> " + f.toString() ) ;
                  }

            }
      }
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17009540
here the object class is in the same package as that of the  class having the method.

thats why you are able to get the details of the protected and default fiellds also.

if the method needs to display the field values of any object then the object should have getter methods for all non - public fields
0
 

Author Comment

by:jell-o
ID: 17009543
Oh yeah...increased the points a bit.
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17009579
you can check if the field is private or protected,

based on that find the getter method for that attribute,

suppose if you have a private attribute parameter1, then the getter for that would be getParameter1()

you can get the method name and field name and compare whether the method is corresponding getter of that field,

if ( methodName.subString(3,methodName.length).equalsIgnoreCase ( fieldName ) )
{
return object =  methodName.invoke ( new Object[1] ) ;
}
0
 

Author Comment

by:jell-o
ID: 17009809
Thanks mukundha_expert !
I didn't refresh the page so I missed your posts, sorry about that.

I'm ok if it doesn't work with private fields.
Here's what I tried. Basically just copied you're code snippet and changed the method into static and deleted the exceptions.

public class Test {
      public String parameter1 = "one";
      public String parameter2 = "two";
      public String parameter3 = "three";

    public static void displayFields (Object obj)
    {
         Field[] field         = obj.getClass().getDeclaredFields();
         Method[] method = obj.getClass().getDeclaredMethods();
         
         for (int i = 0; i < field.length; i++)
         {
              int modifier = field[i].getModifiers() ;
              if ( modifier != Modifier.PRIVATE )
              {
                   Object f = field[i].get(ob) ;
                   System.out.println (field[i].getName() + " -> " + f.toString() ) ;
              }
         }
    }

      public static void main(String[] args) {
            Test t = new Test();
            displayFields(t);  // this how I'd like it to work :)
      }
}


Right now I'm getting some errors about Field[], Method[] and Modifier ("cannot be resolved to a type" & "cannot be resolved").
Like I said...I'm not too good at Java :D The whole Reflection was new to me.
0
 
LVL 10

Expert Comment

by:mukundha_expert
ID: 17009913
Its working fine now,

few compilation errors,
changes to be done,

1. public static void displayFields (Object obj) throws IllegalArgumentException, IllegalAccessException
   
2. Object f = field[i].get(obj) ;

3.  public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
0
 
LVL 10

Accepted Solution

by:
mukundha_expert earned 900 total points
ID: 17009925
hae you imported all the classes??

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
0
 

Author Comment

by:jell-o
ID: 17010066
Yes...it's working now!

Thanks for you're help !!!
Increased the points :)
0
 

Author Comment

by:jell-o
ID: 17010100
...I corrected those compilation errors.
I also hadn't imported all the necessary classes.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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:

588 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