1

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

4 Answers4

1

Sounds complicated. Just use XStream.

String xml = new XStream().toXML(whatever);
Zutty
  • 5,357
  • 26
  • 31
  • 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? –  Apr 02 '13 at 20:08
0

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.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

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?

Community
  • 1
  • 1
NilsH
  • 13,705
  • 4
  • 41
  • 59
0

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());    
}
AlexR
  • 114,158
  • 16
  • 130
  • 208