vendredi 8 janvier 2021

List all methods and their return types from .class file in given path in java

I was trying to read all methods and their return types from already complied .class files from the external path to see the structure of the file. If the compiled file is in your System or can be imported (eg String.class) then it's easy we can simply call this method and get the result. But is there a way to solve this problem for an externally compiled .class file?

public class JavaMethodsNameGeneration {
    public static void main(String[] args) {
        String path = "C:\user\project\MyFile.class";
        System.out.println(generateMethodNameToFile(String.class));//Write the output string to file

    }
    public static String generateMethodNameToFile(Class className){

        Method[] methods = className.getMethods();
        StringBuilder stringBuilder = new StringBuilder();
        Arrays.stream(methods).forEach(method -> {
            stringBuilder.append(method.getName()).append("(");
            Class<?>[] parameterTypes = method.getParameterTypes();
            if(parameterTypes.length>0){
                Arrays.stream(parameterTypes).forEach(p->{
                    stringBuilder.append(p.getSimpleName()).append(",");
                });
            }
            else{
                stringBuilder.append(" ");
            }
            stringBuilder.setLength(Math.max(stringBuilder.length()-1,0));
            stringBuilder.append(")").append(" : ").append(method.getReturnType().equals(Void.class)?"void": method.getReturnType().getSimpleName());
            if(method.getExceptionTypes().length>0){
                stringBuilder.append(" throws ").append(Arrays.stream(method.getExceptionTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ")));
            }
            stringBuilder.append(System.lineSeparator());
        });
        return stringBuilder.toString();
    }
}







Aucun commentaire:

Enregistrer un commentaire