1

How do i get all of the class names for a .java file using reflection.

When i run the following code it only prints out Boat. I have tried making an array of Classes like:

Class c[] = Class.forName("boat.Boat") 

but it results in a syntax error

public class Reflection {
public static void main(String[] args) {
    try {           
         Class c = Class.forName("boat.Boat");
         System.out.println(c.getSimpleName()); 
    } catch(Exception e) {
        e.printStackTrace();
    }
  }
}

Boat.java

package boat;
public class Boat extends Vehicle {
     public Boat() {}
}

class Vehicle {
     public Vehicle() {
         name = "";
     }
     private name;
}
1
  • You can't as far as I know without reading the Java source file and parsing it that way. Once the class is compiled it retains no knowledge of the source file location. You can make some educated guesses, like a public class could have come from a Java source file of a similar name, but you can't even do this for the non public classes. Commented Apr 12, 2013 at 7:15

4 Answers 4

3

Even if you write multiple classes in a single .java file (with only one public class), you will get multiple .class files. Hence, you cannot get the list of classes from .java file.

You do have an option of writing a custom parser to parse the .java file and retrieve the class names. Not sure what would be the use of that?

Sign up to request clarification or add additional context in comments.

Comments

0

It is the .class file we are providing in Class.forName(""); not .java file. So there is no provision to get all classes from .java file with the usage of Class.forName() method.

Comments

0

If you are willing to use additional libraries you can use Reflections Project that allows you to search for classes listed in a package.

 Reflections reflections = new Reflections("my.package.prefix");
 //or
 Reflections reflections = new Reflections(ClasspathHelper.forPackage("my.package.prefix"), 
      new SubTypesScanner(), new TypesAnnotationScanner(), new FilterBuilder().includePackage(...), ...);

 //or using the ConfigurationBuilder
 new Reflections(new ConfigurationBuilder()
      .filterInputsBy(new FilterBuilder().includePackage("my.project.prefix"))
      .setUrls(ClasspathHelper.forPackage("my.project.prefix"))
      .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...));

 //then query, for example:
 Set<Class<? extends Module>> modules = reflections.getSubTypesOf(com.google.inject.Module.class);
 Set<Class<?>> singletons =             reflections.getTypesAnnotatedWith(javax.inject.Singleton.class);

 Set<String> properties =       reflections.getResources(Pattern.compile(".*\\.properties"));
 Set<Constructor> injectables = reflections.getConstructorsAnnotatedWith(javax.inject.Inject.class);
 Set<Method> deprecateds =      reflections.getMethodsAnnotatedWith(javax.ws.rs.Path.class);
 Set<Field> ids =               reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);

 Set<Method> someMethods =      reflections.getMethodsMatchParams(long.class, int.class);
 Set<Method> voidMethods =      reflections.getMethodsReturn(void.class);
 Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(PathParam.class);
 Set<Method> floatToString =    reflections.getConverters(Float.class, String.class);

As you can see you can search with different filters. I don't think you can't do for java file but you can search all the classes for package name.

Comments

0

You can get the superclass of class Boat by calling getSuperclass() on the Class object:

Class<?> c = Boat.class;

Class<?> superClass = c.getSuperclass();
System.out.println(superClass.getSimpleName());  // will print: Vehicle

Look at the API documentation for java.lang.Class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.