mardi 20 octobre 2020

how to get only the specific return type and method names without fully qualified return types and method names in java

By using the following way,

Class c = Class.forName("java.lang.Double");
Method[] m = c.getDeclaredMethods();
for(Method m1 : m)
System.out.println(m1);

the output is:

public boolean java.lang.Double.equals(java.lang.Object)
public static java.lang.String java.lang.Double.toString(double)
public java.lang.String java.lang.Double.toString()
public int java.lang.Double.hashCode()
-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------

Where I need to make changes to get return type and method names without package name to get the desired output as:

public boolean equals(Object)
public static String toString(double)
public String toString()
public int hashCode()
--------------------------------------------
--------------------------------------------
--------------------------------------------

Got the solution, by breaking the whole method into several parts, taking modifier, return type, method name and parameter name separately.

Method[] m = c.getDeclaredMethods();
    Parameter[] param;
    int paramLen;
    for(Method m1 : m){
      System.out.print(Modifier.toString(m1.getModifiers()) + " ");
      System.out.print(m1.getReturnType().getSimpleName());
      System.out.print(" ");
      System.out.print(m1.getName() + "(");
      param = m1.getParameters();
      paramLen = param.length;
      for(Parameter param1 : param){
        System.out.print(param1.getType().getSimpleName() + " " + param1.getName());
        if(--paramLen > 0)
        System.out.print(", ");
      }
    System.out.println(")");




Aucun commentaire:

Enregistrer un commentaire