aspose file tools*
The moose likes Beginning Java and the fly likes Trying to Understand Class Literal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trying to Understand Class Literal" Watch "Trying to Understand Class Literal" New topic
Author

Trying to Understand Class Literal

Michael Craghead
Greenhorn

Joined: Mar 12, 2006
Posts: 12
I ran across this code at work and I don't understand it:



I even read the section in "Just Java 2" and still don't understand what's going on. The class that this method is from is MessageTest. It looks like it would be recursive, but I don't think it works that way. If it's not recursive it doesn't look like it does anything. I'm probably overlooking the obvious, but please point me to the obvious. Thanks.



[edit]Add code tags. CR[/edit]
[ September 25, 2008: Message edited by: Campbell Ritchie ]

Michael K. Craghead<br />�Timba or muerte!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

MessageTest.class just returns a Class object. It's like calling getClass() on an instance of MessageTest, but without the need of an instance.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Michael Craghead
Greenhorn

Joined: Mar 12, 2006
Posts: 12
Originally posted by Rob Prime:
MessageTest.class just returns a Class object. It's like calling getClass() on an instance of MessageTest, but without the need of an instance.


OK, but I still don't see the point of the following in the getResourceAsStream method:

final InputStream stream = MessageTest.class.getResourceAsStream(name);

It looks like it's getting the class object in order to call getResourceAsStream(), when getResourceAsStream is already static, and you're already inside the method. I guess another way to put it is, why do I need a class object to call a method that I'm already in? You've still lost me.



[ September 25, 2008: Message edited by: Michael Craghead ]
[ September 25, 2008: Message edited by: Michael Craghead ]
Michael Craghead
Greenhorn

Joined: Mar 12, 2006
Posts: 12
Never mind. I see now that getResourceAsStream() is not only the method in class MessageTest, but also a method in class Class. Now it makes sense. Thanks.

Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
If the classes in the runtime were loaded by different class loaders, they will return resources differently - based on the class loader.

The previous coder has decided that MessageTest is coming from the same place as name, so they decided to use that.


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trying to Understand Class Literal