Solved

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

Posted on 2006-06-29
15
201 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
[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
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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
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 225 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
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:
Suggested Courses

626 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