[3125] in java-interest
Re: Q on static method reference to class
daemon@ATHENA.MIT.EDU (Thomas Ball)
Tue Oct 31 22:27:25 1995
Date: Tue, 31 Oct 1995 17:48:26 -0800
From: Thomas.Ball@Eng.Sun.COM (Thomas Ball)
To: rbk@ibeam.jf.intel.com
Cc: java-interest@java.Eng.Sun.COM
> Suppose I want to refer to the class in a static method, eg to get the name
> of the class, or create a new instance... How do I do this? If I'm in an
> instance method, I can say (eg) "getClass().getName()". However, trying
> various things in a static method gets compiler errors. Surely there must
> be a way to do this cleanly without referring to the class by name?
Implied in your question is the assumption that you can't just create
an instance of a class in one of its static methods, but you can:
public class test {
int num;
test(int num) {
this.num = num;
}
public static void main(String argv[]) {
test t = new test(123);
String name = t.getClass().getName();
System.out.println("class = " + name + ", object = " + t);
}
}
There is no easy way to divine that name from inside a static method
(unless you do the above), but then the class is already defined.
C has a similar feature when defining structs, where you can reference
that struct inside of itself (linked-lists are usually done that way).
Tom Ball
Java Products Group
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com