Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class name of any java file

Tags:

java

Does java offer a simple way to do this?

I know how to get this using Foo.class.getName())

But how would I be able to do this for any object I may be passing in through some method? Say

public String getClass(File file){
          // Get file class
}

Where file is some java file with a .java extension. I know it works if I directly hard code the name of the java class into Foo.class.getName(), but my approach at this includes java files not found in the current directory or package. Anyone guide me in the right direction? Thanks in advance.

like image 869
Ceelos Avatar asked Dec 26 '22 10:12

Ceelos


2 Answers

Well .java files need to have the same name as the class or enum within, so we could just use the file name:

public String getClass(File file){
  return removeExtension(file.getName());
}

removeExtension has many different ways of achieving, here is just one:

public static String removeExtension(String file){
  return file.replaceFirst("[.][^.]+$", "");
}

More here: How to get the filename without the extension in Java?

...the reason behind me wanting to do is is so that I can count the methods within the class.

OK, well this is not the way to do it, you should look into reflection: What is reflection and why is it useful?

like image 56
weston Avatar answered Dec 28 '22 01:12

weston


Here is example code that gets classname from source with help of JavaParser.

This also works for wrongly named source files.

import com.github.javaparser.*;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.body.*;
import java.io.*;
import java.util.*;

public class ClassnameLister {

    private static String parseClassname(File filename) throws Exception {
        try (FileInputStream fin = new FileInputStream(filename)) {
            CompilationUnit cu = JavaParser.parse(fin);
            String packagePrefix = cu.getPackage().getName().toString();
            if (!packagePrefix.isEmpty()) packagePrefix += ".";
            for (TypeDeclaration type : cu.getTypes())
                if (type instanceOf ClassOrInterfaceDeclaration 
                        && ModifierSet.isPublic(type.getModifiers()))
                    return packagePrefix + type.getName();
        }
        return null;
    }

    public static void main(final String[] args) throws Exception {
        System.out.println(parseClassname(new File(args[0])));
    }
}
like image 28
Vadzim Avatar answered Dec 28 '22 00:12

Vadzim