27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

General <strong>Java</strong> Questions I<br />

You can then read the file by using a reader (or whatever you choose),<br />

e.g.:<br />

_istream = new BufferedReader( new<br />

InputStreamReader(fileURL.openStream()) );<br />

-j<br />

o h n e w e b e r<br />

Or, simpler<br />

getClass().getResourcesAsStream("file.txt"), but you must be sure that<br />

file is in the same directory ( package ) as your class, otherwise you<br />

need play with getClassLoader().getResourceAsStream( "/file.txt" );<br />

--<br />

Oleg<br />

Q: Difference between loading and instantiating a class???<br />

Well, the subject says it all. What is the difference between loading and instantiating<br />

a class in a JVM.<br />

Second question: What would happen if at runtime I update a class file? Will the JVM<br />

know to use that instead?<br />

Answer: The difference is that when a class is loaded by a ClassLoader it is read in<br />

as a stream of bytes, presumably from a file, but it could just as easily be from over<br />

the network, and then processed or "cooked" into a representation that the VM can<br />

use to make instances of Objects of that classes type. This last part is the<br />

instantiation. You can load a class at runtime with:<br />

Class.forName( "MyClass" );<br />

and instantiate one with:<br />

MyClass mc = Class.forName( "MyClass" ).newInstance();<br />

Cool, ehh. You don't have to know the name of a class at compile time.<br />

>Second question: What would happen if at runtime I update a class file?<br />

>Will the JVM know to use that instead?<br />

Loaded classes are cached because it's quite costly to do the "cooking" I mentioned<br />

above. So it will not be loaded. You may create a separate ClassLoader with new<br />

SecureClassLoader but that will cause all classes _it_ loads to be loaded from this<br />

new ClassLoader but that's not what<br />

you want.<br />

I don't know if you can specify that a class should be loaded from disk again using the<br />

normal ClassLoader. You could very easily make your own ClassLoader in which<br />

case you would have explicit control over such things. Look at java.lang.ClassLoader<br />

and java.lang.Class.<br />

--<br />

Michael B. Allen<br />

file:///F|/350_t/350_tips/general_java-I.htm (18 of 31) [2002-02-27 21:18:17]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!