Search code examples
javastatic-analysis

How to search through java files for attributes/ parameters of a certain type


I have a folder with java files. I would like to find out if a class contains an attribute of type X without compiling the project, i.e. I don't want to use reflection. How can I achieve this in a static way?


Solution

  • Have you considered using JBoss Forge's roster library?

    String javaCode = "public class MyClass{ private String field;} public class AnotherClass {}";
    
    JavaUnit unit = Roaster.parseUnit(javaCode);
    
    JavaClassSource myClass = unit.getGoverningType();
    JavaClassSource anotherClass = (JavaClassSource) unit.getTopLevelTypes().get(1);