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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

http://www.pobox.com/~skeet<br />

this advice first was published on comp.lang.java.programmer<br />

Q: I find such function, but in Class class. Is it possible to use it (or something like<br />

this) in another class? Exactly I would like call: super.super.method1();<br />

Answer: No, you can only access methods of your direct ancestor.<br />

The only way to do this is by using reflection:<br />

import java.lang.reflect.*;<br />

Class superduper = this.getClass().<br />

getSuperClass().<br />

getSuperClass();<br />

Method ssMethod = superduper.getMethod("method1",null);<br />

ssMethod.invoke(this,null);<br />

(I didn't check the exact syntax and parameters of the above code.)<br />

However the necessity to skip a hierarchy shows that there is something wrong with<br />

the design of your application. You should fix this instead of using dirty tricks like the<br />

above.<br />

---<br />

Carl Rosenberger<br />

db4o - database for objects - http://www.db4o.com<br />

Q: If anybody can provide some tips on how to design this smartly...<br />

Q: I am facing a problem that might sound common to you all. I have to write a<br />

switch statement with 40 case statement. I am wondering if there can be some way to<br />

reduce this. If anybody can provide some tips on how to design this smartly. ;)<br />

Answer: The alternatives are:<br />

an array you index into to get values or delegates.<br />

an array you binary search.<br />

--<br />

Roedy Green<br />

Q: I want to use some java variables , across multiple java files. Is there some<br />

thing like a "extern in C" in java ??<br />

Answer: If you want to share constants, the usual way is to create a class like this:<br />

public class My_Constants {<br />

public static final int ID_OK = 1;<br />

public static final int ID_CANCEL = 2;<br />

}<br />

public static final String MSG_OK = "Okay.";<br />

public static final String MSG_ERROR = "An error occurred.";<br />

If you want to share a single object instance across your application, use the<br />

Singleton pattern.<br />

Actually, the more common way is to create an interface, like this:<br />

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

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

Saved successfully!

Ooh no, something went wrong!