Using Java reflection:
- How can I get all the methods of a given object (private, protected, public etc)
- And perhaps create a structural representation of the class
- And finally, serialize the object into String or byte array
Does this idea look sound? or this won't get me anywhere?
What I'm trying to achieve is to be able to:
- Serialize any
java.lang.Object
into byte array or String - Class / Objects that don't implement
Serializable
will be thrown into my application for serialization
-
2Did you try anything? Just check the documentation about Reflection.Sudhanshu Umalkar– Sudhanshu Umalkar04/02/2013 09:03:44Commented Apr 2, 2013 at 9:03
-
Why do you need to do it for all kinds of objects? If you don't need it for all obejcts, why are existing serialization libs not satisfactory for you?ppeterka– ppeterka04/02/2013 09:04:34Commented Apr 2, 2013 at 9:04
4 Answers 4
Sounds complicated. Just use XStream.
String xml = new XStream().toXML(whatever);
-
my concern with this XML marshaling is that actual types might get lost, does this Xtream library return the same object type? Or just String?user1302575– user130257504/02/2013 20:08:06Commented Apr 2, 2013 at 20:08
Question 1: How to get all methods of a class.
getDeclaredMethods will provide you with access to all of the methods on a class.
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
Example: Method[] methods = Integer.class.getDeclaredMethods();
Question 2: Create a Structural Representation of a Class
I'm not sure why you would need to do this since it already exists. You can always retrieve an object's class, which provides you with its structure.
To get all methods and fields for a class, use getDeclaredMethods
and getDeclaredFields
. I'm not sure if you can use it to re-compose a non serializable class though, and I'm not sure I would either. But maybe you can find some ideas here: How to serialize a non-serializable in Java?
Class.getDeclaredMethods()
and Class.getDeclaredFields()
return methods and fields with any visibility declared in current class only. These methods do not return inherited stuff. To do this you have to iterate over the class hierarchy and call these methods for each super class, i.e.:
List<Method> methods = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class c = clazz; c != null; c = c.getSuperClass()) {
methods.add(c.getDeclaredMethods());
fields.add(c.getDeclaredFields());
}