Существует много способов добиться того, что вам нужно. Хотя мне было бы интересно , почему вам нужно.
toString()
. см.: http://www.javapractices.com/topic/TopicAction.do?Id=55 UserPrettyPrinter
. public interface UserPrettyPrinter {
string print(User);
}
public class PrintUserInJSON implements UserPrettyPrinter {
string print(User user) {
//implement the algo here
}
}
вы также можете реализовать: public class PrintUserInXML implements UserPrettyPrinter {
string print(User user) {
//implement the algo here
}
}
public class PrintObjectBasicAlgo {
String print(Object obj) {
/* i write pseudo code here. just ask if you cannot implement this
this would help: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
Class class = Obj.getClass();
Filed[] allVariables = class.getAllFieldsByReflection();
ArrayList keys = new ArrayList;
ArrayList values = new ArrayList;
for(Field field : allVariables) {
Object value = reflectionGetValueOfField( field, obj );
keys.add( field.getName());
values.add(value.toString());
}
now that you have the keys and values, you can generate a string in anyway you like
*/
}
}