-2
public class A {

    public class B{

        public class C {

        }

    }

    public class D {

    }
}

If this is my example how I write a java code to get then names of classes like A,B,C and D in a string. Help will highly be appreciated. Thank you

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Haseb Ansari
  • 587
  • 1
  • 7
  • 23

2 Answers2

2

I came up with this reflection based answer:

public static List<String> getClassNames(Class baseClass) {
    List<String> classNames = new ArrayList<String>();
    classNames.add(baseClass.getSimpleName());
    for (Class subclass: baseClass.getClasses()) {
        classNames.addAll(getClassNames(subclass));
    }
    return classNames;
}

Which returned [A, D, B, C]. You didn't make it clear if order is important.

Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
1

If the class to parse is not in your classpath (and you have only the source code), you need to parse it and to be compatible with any possible java code you should use a java parser. There are several. You can just google it.

For example: https://github.com/javaparser/javaparser

If the class is in your classpath, you can use reflection.

Marco Altieri
  • 3,726
  • 2
  • 33
  • 47
  • 1
    new VoidVisitorAdapter() { @Override public void visit(ClassOrInterfaceDeclaration n, Object arg) { super.visit(n, arg); System.out.println(" * " + n.getName()); } }.visit(JavaParser.parse(file), null); – Federico Tomassetti Feb 07 '16 at 12:19