Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can doing reflection on classes accidentally invoke methods (e.g. static constructors)?

I've written some code to analyze all of the packages/classes that come bundled with the Java 1.6 API. This means iterating over all of the classes doing reflection things with them to generate stats.

None of this code actually creates any instances of classes or invokes any methods from them: I'm just doing stuff like calling getDeclaredMethods() and getDeclaredFields().

This is fine with the majority of classes (pretty much anything in a java.* or javax.* package). However some other classes break my program, throwing exceptions like:

WARNING: "IOP00710208: (INTERNAL) Unable to determine local hostname from InetAddress.getLocalHost().getHostName()"
org.omg.CORBA.INTERNAL:   vmcid: SUN  minor code: 208  completed: No

This seems like an odd issue. Could it be that, when I refer to that class (e.g. by calling Class.forName()), it invokes static constructors in that class? Like if the class is a factory class, or has final fields which have already been instantiated?

I got around the problem of classes throwing exceptions when I looked at them, by putting everything in a try/catch(Throwable) block.

I am curious as to what's causing those exceptions though. Is it, like I thought, static constructors and similar? I'm not able to find the source (maybe I'm just looking in the wrong place...!) for those classes so I can't check myself...

like image 973
Erinaceous Avatar asked Mar 12 '26 14:03

Erinaceous


2 Answers

Yes, causing a class to be loaded (e.g through class.forName()) can cause static initializers to be run. In the below example, loading this class will print out "Hello":

public class Demo{   
  static{
    System.out.println("Hello");
  }
}
like image 67
DNA Avatar answered Mar 14 '26 02:03

DNA


The parameterless forName explicitly loads the class it's being called with, and that's when static initializers are called (more or less). You could try calling the variant that takes boolean initialize.

like image 38
Dave Newton Avatar answered Mar 14 '26 02:03

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!