Ceelos Ceelos - 1 year ago 70
Java Question

How to get class name of any java file

Does java offer a simple way to do this?

I know how to get this using


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
, 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.

Answer Source

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 file name without the extension?

...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?