Is there something in APEX like __file__ (Python) or __FILE__ (PHP and C++)? Or even something like this in Java:

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");

2 Answers 2


The thing I think you're describing is a feature of languages called reflection or introspection.

Apex does not really have either of those. The closest thing we have is the Type class, which we can use to dynamically instantiate objects.

// Type.forName() allows us to use a string to determine which class to instantiate
// It returns an Object though, so this isn't of much use beyond using it for things that
//   extend other classes or implement interfaces.
// Objects need to be cast to another type to really be of any use, and the typecast can't
//   be dynamic (the type needs to be known at compile-time)
MyClass mcInstance = (MyClass)Type.forName('MyClass').newInstance();

If you want/need the name of a class inside of that class, then I think the best we can do is something like this

public class MyClass{
    // "final" makes the variable a constant (write once)
    public final className;

    public MyClass(){
        // <class name>.class gets you an instance of System.Type
        // Basically, it's the statically compilable version of Type.forName().newInstance()
        // System.Type has a getName() method which returns the name of the type
        this.className = MyClass.class.getName();
  • Thanks. I've never heard anyone refer to __ FILE __ as inflection. It's just a useful global that I hoped would be there. Maybe the terminology has to do with compiled vs. interpreted languages? I'm familiar with the Java way and I'm not shocked APEX falls short. I just want the file name to be determined dynamically so I can pre-pend it to USER_DEBUG messages. At the moment all I see is a line number which isn't much help unless I know the file. Commented Feb 19, 2020 at 21:48

Not sure if I'm following you question (getting a file name vs. getting the Apex class name), but I've used this in the past and seems to faithfully get the current Apex class name:

String className = String.valueOf(this).substring(0,String.valueOf(this).indexOf(':'));
  • 1
    That might not work in pure static contexts, but I guess that's fine for classes that you instantiate, which is most anything aside from Aura/Rest/etc.
    – sfdcfox
    Commented Feb 19, 2020 at 22:43
  • 1
    Yes, I just ran into an issue with this for static methods.
    – hgolov
    Commented Aug 1, 2021 at 9:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .