File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes static {} Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "static {}" Watch "static {}" New topic
Author

static {}

Serge de Schaetzen
Greenhorn

Joined: Jun 08, 2005
Posts: 8
I'm wondering if there's a way to find out if a class has a static {} method, without having the static {} method being invoked ?

Ex:
public class A
{
static
{
// do some code.
}
}

if from another class you use reflection, Class.forName("A"), the code in the static method will be invoked, although you haven't created any instance of the class.

Is there any SecurityManager setting that can be used to avoid this ?

Serge.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
The only way I could think of find out would be to locate the .class file (not loading the class just finding the file), read it in like a regular file and parse it.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

slightly easier may be to use javap in an external process to query the class and look for a static block. Not perfect, but it's a solution.
Santhosh Kumar
Ranch Hand

Joined: Nov 07, 2000
Posts: 242
There are lots of Java byte code engineering libraries. You can use one of them. That would be suggested approach instead of you parsing or invoking a separate native process to reverse engineer the .class file.

One of them is http://jakarta.apache.org/bcel

Using these, you can access the information about the class just by invoking appropriate methods.

Hope this helps.
Serge de Schaetzen
Greenhorn

Joined: Jun 08, 2005
Posts: 8
Thanks,

I think that using a bytecode library is the way to go.
At least, it avoids me having to do the parsing.

Serge.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static {}