I'm trying to use Java's reflection library to produce documentation for my codebase. I realize that's unwise in itself; that's a decision that predates me.
I'd like to print human-readable return types. So if a method returns an ArrayList<String>
, I'd like to say that. Right now I've figured out how to get it to say java.util.ArrayList<java.lang.String>
. I could use string methods to fix it, but I'm hoping there's a better way.
Here's what I've got that prints that sub-optimal version:
class ToBeReflectedOn {
public static ArrayList<String> returnsAStringList() {
return new ArrayList<String>();
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ToBeReflectedOn toBeReflectedOn = new ToBeReflectedOn();
Class c = toBeReflectedOn.getClass();
Method returnsAStringListMethod = Arrays.stream(c.getDeclaredMethods())
.filter(m -> m.getName() == "returnsAStringList")
.collect(Collectors.toList()).get(0);
System.out.println(
"\nName: " + returnsAStringListMethod.getName()
+ "\nDeclaring Class: " + returnsAStringListMethod.getDeclaringClass().getName()
+ "\nReturn Type: " + returnsAStringListMethod.getReturnType().getName()
+ "\nGeneric Return Type: " + returnsAStringListMethod.getGenericReturnType().getTypeName()
);
}
}
Which outputs:
Name: returnsAStringList
Declaring Class: ToBeReflectedOn
Return Type: java.util.ArrayList
Generic Return Type: java.util.ArrayList<java.lang.String>
You can play with it here: https://ideone.com/qi4wD5
How can I make it print ArrayList<String>
instead?
Aucun commentaire:
Enregistrer un commentaire