[3126] in java-interest
Re: Q on static method reference to class
daemon@ATHENA.MIT.EDU (Bob Beck)
Tue Oct 31 22:28:09 1995
Date: Tue, 31 Oct 95 18:02 PST
To: Thomas.Ball@Eng.Sun.COM (Thomas Ball), rbk@ibeam.jf.intel.com
From: Bob Beck <rbk@ibeam.jf.intel.com>
Cc: java-interest@java.Eng.Sun.COM
At 05:48 PM 10/31/95 -0800, Thomas Ball wrote:
>> 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).
Thanks for the quick response! I was trying to avoid creating an instance
in the class method. This seems to be an area where Java isn't quite as
clean as (eg) Smalltalk ... in Smalltalk, a class method can refer to
"super" and things work as expected. Also, a class method can say (eg)
"self name" to get the name. Ie, the class is a "first class" object; it
doesn't seem quite true in Java...
There is a class object, but it doesn't seem wired into the method
resolution process quite right. Since an instance method can say getClass()
to get a reference to the class, why can't a class method do something to
get it? Intuitively, "this" in a class method would refer to the class.
>Tom Ball
>Java Products Group
--
Bob Beck rbk@ibeam.intel.com CompuServe: 71674,106
Intel Corporation (503)264-8856 AOL: RDBeck
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com