JDK-4851444 : (reflect) equivalent of sun.reflect.Reflection.getCallerClass should be exposed
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 1.4.1
  • Priority: P4
  • Status: Resolved
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2003-04-21
  • Updated: 2017-02-17
  • Resolved: 2017-02-17
Related Reports
Duplicate :  
Relates :  
Relates :  

Name: rmT116609			Date: 04/21/2003

Many Java technologies are relying on a dynamic factory pattern, where a factory class looks for the actual implementation by locating the implementation class through META-INF/services file or by similar means.
JAXP and JAXB are typical examples.

Essentially, those are doing Class.forName(className), but here's the problem.

The caller of Class.forName() is JAXB or JAXP itself, and those API jars
does NOT typically reside in the domain of the application class loader. Instead, it often lives in the app server's own lib directory, or the endorsed lib directory. Therefore, when those factory classes try to locate a service description file or when it calls the Class.forName(), the class loader used for it is the class loader that loaded JAXP/JAXB.

This prevents the factory from looking at the application's class loader, and causing a problem that is hard for average users to fix.

Since the details of class loading is usually not understood by average users, it would be nice if those factory classes can automatically use the caller's class loader, just like Class.forName(String).

I found out that the sun.reflect.Reflection.getCallerClass(int) method is used inside the Class.forName() method to find the caller's class loader, but unfortunately this method is not publicly available, so it cannot be reliably used, hence this RFE.

One possibility seems to be to add the Class getClass() method to the java.lang.StackTraceElement class, so that I can access a Class object (not just a class name). Then I can do:

try {
	throw new Exception();
} catch( Exception e ) {
	// examine the stack trace elements to find out the caller's class loader

If I could obtain the list of the current StackTraceElement[] without throwing a dummy exception, that would be even better.

Technologies like JAXB (Java Architecture for XML Binding) would benefit from this enhancement.

It will in turn improve the user experience of those technologies, and make Java less error-prone, easier to user

Currently those technologies may allow users to pass in a reference to a class loader. But many users don't understand the details of class loading and therefore it tends to be ignored.
(Review ID: 184519) 

The StackWalker API provides a getCallerClass() method, as well as related, more flexible, functionality via the RETAIN_CLASS_REFERENCE option.