lokilindo
lokilindo

Reputation: 702

How to create a .txt file with the name of the class that called the method?

I am new to programming, so let's see if I can explain this well enough.

I am making a Java package. In one of the classes there is a method that creates a file. The name of that file I have it set up as "file.txt", but I want to change it.

Let's say there is a user working on a new project and he imports the library package (the one I am working on). I want for the file that is created to take the name of the class in which the user is working on. For example if the user calls it in a class named Main, I want the file to be called main.txt or Main.txt.

If this is not clear enough please let me know, I'll try to explain it better.

Thanks

Edit: I've tried the getClass().getSimpleName() but it's not working exactly like I want it to. The method is located inside a library called library and the class is called Main.class but is being used by a use that imported the library library and is working on a class called SuperMario.class I want the text file to be called SuperMario.txt instead with getClass().getSimpleName() applied to my method the file will be called Main.txt, because that is the name of the class the method is in. Unfortunately I can't have the method pass the name as a parameter. Can anyone think of a way around this?

Upvotes: 1

Views: 168

Answers (1)

GaspardP
GaspardP

Reputation: 890

In your library, use stacktrace :

public class Called {

public static void calledMethod() {
        System.out.println(Thread.currentThread().getStackTrace()[2].getClassName());
        // stackTrace 0 is get stack trace.
        // stack trace 1 is calledMethod
        // stack trace 2 is the calling method aka main in
    }
}

The result will be

eu.plop.test.TestClass

You had to search after stacktrace to see if you want the filename, class name, method's name... and then some string works to remove the package if unused.

Upvotes: 3

Related Questions