Solved

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

Posted on 2006-06-29
15
196 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 92

Expert Comment

by:objects
ID: 17008436
0
 
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
 
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
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).

 
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
powerN  challenge 3 47
thymeleaf natural templating vs JSP 2 24
github account with ecipse 1 16
Java DateChooser? 2 5
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…
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 …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.

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

13 Experts available now in Live!

Get 1:1 Help Now