You could accomplish this using reflection, up to a point.
Using java.lang.Class#getDeclaredFields() you can retrieve an array of Field objects, which represent fields declared by that class (excluding inherited fields).
If you loop over this array you could use the java.lang.reflect.Field#getModifiers() method to determine which modifiers accompany the field. By making use the public constants defined by the java.lang.reflect.Modifier class and bitwise operations, you can filter out the fields declared as private and static.
Once you do that it's simply a matter of making the private field accessible to the reflection API, by calling java.lang.reflect.Field#setAccessible() with boolean value true. Then you can use the java.lang.reflect.Field#get() method to retrieve the field's value as an Object reference (primitives will be autoboxed, assuming you're using atleast Java 5).
Unfortunately, from there on out your options are rather limited, if you need to stay completely dynamic - you would basically be condemned to use the information returned by the toString() method, which is more often than not completely useless. Though, if you know which type you are inspecting and you its layout you can really get down and dirty with its privates.
Ok, that last bit didn't come out right...
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Joined: Oct 26, 2007
I have done the followings in my code. and got the result. But not aware of, if it is optimized solution or not.
There may be nothing to improve performance, but you might need to improve correctness. Are you not seeing any error messages printed here?
If you have any non-static fields in the class DatePatterns, your code would probably throw an exception. To avoid this, you can check whether a field is static using
If you have private fields you want to access, you will probably need
Also, the use of field.get(String.class) in the code above is incorrect. The way you're using it would be used if you were trying to get data from the String.class instance, i.e. from the instance of class Class that represents the class String. But no, you're trying to get data from the DatePatterns class. String.class has nothing to do with this. As it happens, for static fields, the argument to the get() method is ignored anyway, which is why you haven't seen an error from this. If one of your fields were not static, then you'd get an exception complaining that String.class is not a DatePatterns instance. Anyway, the code right now is misleading at best. You should probably replace field.get(String.class) with field.get(null). If you need to access non-static fields, you'd use an instance of DatePatterns as the argument instead.