Getting a reference to the class from a static context
I have the objective of creating an abstract super class of a set of runtime classes and I want to add a static method to the super class that can get a reference to the the runtime class and do operations on it.
Normally I would get the reference by saying "this.class", but because the method must be static there is no "this" reference. How can I get the reference to the class from within the static context?
[432 byte] By [
fazle] at [2007-9-30 21:32:42]

You cannot. You can refer to other static instance variables and methods, but there is no instance to reference... the static variables and methods are shared across all instances. If you actually instantiate the class with the 'new' keyword, that instance will have a reference to itself (this) and its ancestors (super). You can call an ancestor or descendant's static methods using the normal static method call notation: Class.method().
Hope that helps.
- Saish
"My karma ran over your dogma." - Anon
Saish at 2007-7-7 3:04:17 >

Actually, just use [class name].class (Double.class will return a Class that describes Double, for example). .class actually is a static variable! The instance way to get a class is this.getClass().
However, realize that this static variable will return the exact class of the class invoking it. It wil not return the subclass unless you use the subclass's name. For example, if I have a class called Car which is extended by StationWagon, PickUpTruck, and Van, then Car.class will return a Class instance about Car. I have to use Van.class to get van's Class variable.
Hope that helps.
hmmm... After rereading that, it's not as clear as I thought.
Are you saying you want to do something like this:
public class Foo
{
public static void doSomething(Foo foo)
{<i>do stuff</i>}
}
public class Roo extends Foo
{<i>stuff</i>}
public class Main
{
public static void main(String[] args)
{Foo f = new Roo();
Foo.doSomething(f);
}
}
Or do you mean you want the class inside of a static method, like this:
public class Foo
{
public static void doSomething()
{
<i>need Foo's class here to do stuff</i>
}
}
If it's the first one, just call foo.getClass() replacing foo with the parameter you use. If it's the second, use Foo.class, replacing Foo with your class's name.