statically calling getClass().getName()

I'm just curious ... I don't need to do this for any reason, but ...

Is it possible to call the getName() method statically for a given class?

public class MyClass
{
    public static void main( String[] args )
    {
        System.out.println( getClass().getName() );
    }
}


ofcourse, the above example produces a compiler error because there is no instatiated "this" object from which to call the method (the method itself is not static).  Is it possible to get the current classname in this manner (from main() -- other than println("MyClass") ?
LVL 33
knightEknightAsked:
Who is Participating?
 
klfConnect With a Mentor Commented:

try

public class MyClass
{
   public static void main( String[] args )
   {
       System.out.println( MyClass.class.getName() );
   }
}
0
 
fi76631Commented:
No. You do not know the type of a class when it is static, only when it is constructed. Consider your class implementing an interface etc.....
0
 
knightEknightAuthor Commented:
I suspected as much ... thanks.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
knightEknightAuthor Commented:
I'm trying to accept your comment as answer, but it won't let me ...
0
 
knightEknightAuthor Commented:
please lock it ... maybe that will work.
0
 
knightEknightAuthor Commented:
as fate would have it ... it works!

ofcourse, you have to _know_ the classname in order to _get_ the classname ... so I don't know how much value this has.  But it does return the fully qualified package name, i.e.  com.test.MyClass  ... for what its worth.

Thanks to both of you.
0
 
roo_jCommented:
try

public class MyClass
{
   public static void main( String[] args )
   {
       System.out.println( this.getClass().getName() );
   }
}
0
 
knightEknightAuthor Commented:
no because "this" has no object reference in the main().  But this would work:


public class MyClass
{
   public static void main( String[] args )
   {
      MyClass mc = new MyClass();
      System.out.println( mc.getClass().getName() );
   }
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.