class - Displaying Field type with Java reflection -
i using reflection in java.
here code:
public string getclassfields(class aclass) { string classfields = ""; field[] fields = aclass.getdeclaredfields(); boolean ispublic; string separator = system.getproperty( "line.separator" ); (field f : fields) { ispublic = modifier.ispublic(f.getmodifiers()); if (ispublic) classfields += "public " + f.gettype() + " " + f.getname() + separator; else classfields += "private " + f.gettype() + " " + f.getname() + separator; } return classfields; }
if fields in class follows:
private int diameter; private colour colour; the code have posted above returns following:
private int diameter private class colour colour how can modify code remove additional 'class' word line:
private class colour colour
right now, you're getting default string representation, provided class#tostring():
converts object string. string representation string "class" or "interface", followed space, , qualified name of class in format returned
getname. ifclassobject represents primitive type, method returns name of primitive type. ifclassobject represents void method returns "void".
so want use different method name of class. change
f.gettype() to
((class) f.gettype()).getname() // or ((class) f.gettype()).getsimplename() side note: don't perform string concatenation in loop that. because has copy string each time, leads quadratic (o(n^2)) asymptotic runtime. use stringbuilder instead.
Comments
Post a Comment