public class generictostring {
String hello = "world";
int i = 42;
public static void main(String args []) {
System.out.println(new generictostring().toString());
// generictostring{i=42, hello=world}
}
public String toString() {
java.util.Hashtable h = new java.util.Hashtable();
Class cls = getClass();
java.lang.reflect.Field[] f = cls.getDeclaredFields();
java.lang.reflect.AccessibleObject.setAccessible(f, true); //jdk1.2
for (int i = 0; i < f.length; i++) {
try {
h.put(f[i].getName(),f[i].get(this));
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (cls.getSuperclass().getSuperclass() != null) {
h.put("super", super.toString());
}
return cls.getName() + h;
}
}Christian Ullenboom wrote:
Hi, your solution is fine, but has some drawbacks:
- it based on inheritance
- an attribute of a subclass cannot overlap an attribute of a superclass (because of hashtable)
So I changed your solution a bit:
// @author Christian Ullenboom
// @url http://java-tutor.com
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
class ToStringHelper {
public static String toString( Object o ) {
ArrayList list = new ArrayList();
toString( o, o.getClass(), list );
return o.getClass().getName().concat( list.toString() );
}
private static void toString( Object o, Class clazz, ArrayList list ) {
Field f[] = clazz.getDeclaredFields();
AccessibleObject.setAccessible( f, true );
for ( int i = 0; i < f.length; i++ ) {
try {
list.add( f[i].getName() + "=" + f[i].get(o) );
}
catch ( IllegalAccessException e ) { e.printStackTrace(); }
}
if ( clazz.getSuperclass().getSuperclass() != null )
toString( o, clazz.getSuperclass(), list );
}
}
class Ober {
int i = 123;
private double d = 3.1415;
}
public class ToStringHelperTest extends Ober {
String hello = "world";
int i = 42;
public static void main(String args[]) {
Ober t = new ToStringHelperTest();
System.out.println( ToStringHelper.toString(t) );
// ToStringHelperTest[hello=world, i=42, i=123, d=3.1415]
}
}Written and compiled by Réal Gagnon ©1998-2005
[ home ]