• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trying to Understand Class Literal

 
Michael Craghead
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MessageTest.class just returns a Class object. It's like calling getClass() on an instance of MessageTest, but without the need of an instance.
 
Michael Craghead
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic