Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1591
  • Last Modified:

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") ?
0
knightEknight
Asked:
knightEknight
1 Solution
 
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
 
knightEknightAuthor Commented:
I'm trying to accept your comment as answer, but it won't let me ...
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
knightEknightAuthor Commented:
please lock it ... maybe that will work.
0
 
klfCommented:

try

public class MyClass
{
   public static void main( String[] args )
   {
       System.out.println( MyClass.class.getName() );
   }
}
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now