Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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

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
jell-o
Asked:
jell-o
1 Solution
 
mukundha_expertCommented:
ya using reflection you can do that
0
 
Ajay-SinghCommented:
try using reflection
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
mukundha_expertCommented:
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
 
mukundha_expertCommented:
if the fields are not private then,

you can get the field values using

returnObjext =   field[i].get ( objectname) ;
0
 
jell-oAuthor Commented:
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
 
mukundha_expertCommented:
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
 
mukundha_expertCommented:
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
 
jell-oAuthor Commented:
Oh yeah...increased the points a bit.
0
 
mukundha_expertCommented:
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
 
jell-oAuthor Commented:
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
 
mukundha_expertCommented:
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
 
mukundha_expertCommented:
hae you imported all the classes??

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
0
 
jell-oAuthor Commented:
Yes...it's working now!

Thanks for you're help !!!
Increased the points :)
0
 
jell-oAuthor Commented:
...I corrected those compilation errors.
I also hadn't imported all the necessary classes.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now