NPE on getEnclosingMethod()

David Holmes david.holmes at oracle.com
Tue Dec 17 00:22:12 UTC 2019


Hi Dennis,

On 17/12/2019 9:12 am, Dennis Gesker wrote:
> Hello OpenJDK list...
> 
> I do hope this is the correct list for user questions. 

OpenJDK lists are for OpenJDK developers not end-users.

> I'm getting a NULL when calling:
> 
> this.getClass().getEnclosingMethod()

As you would if not called from a nested type defined within a method.

assertTrue(this.getClass().getEnclosingMethod() == null);
assertTrue(this.getClass().getEnclosingMethod().getName() == null);

If you pass the first assert you're guaranteed to get a NPE when calling 
getName() on the second.

Cheers,
David
-----

> I was going to file a bug but I'm not yet a contributor and hope to get
> login credentials soon. Any chance an existing member could take a look at
> my unit test below? And, if verified and not duplicate file a bug report on
> my behalf?
> 
> Thanks,
> Dennis
> 
> Using:
> 
> openjdk version "11.0.5-ea" 2019-10-15
> OpenJDK Runtime Environment (build 11.0.5-ea+10-post-Ubuntu-0ubuntu1)
> OpenJDK 64-Bit Server VM (build 11.0.5-ea+10-post-Ubuntu-0ubuntu1, mixed
> mode, sharing)
> 
> The following test compiles (-Xlint:all -Werror) but throws and NPE on
> execution:
> 
> package test;
> 
> import static org.junit.Assert.assertTrue;
> import java.util.logging.Level;
> import java.util.logging.Logger;
> import org.junit.jupiter.api.Test;
> 
> public class CheckForNullEnclosingMethod {
> private Logger logger = Logger.getLogger(this.getClass().getSimpleName());
> 
> @Test
> public void iSeemToBeLost() {
> 
> if (this.getClass().getEnclosingMethod() == null) {
> logger.logp(Level.SEVERE, this.getClass().getName(),
> this.getClass().getEnclosingMethod().getName(),
> "What method am I in?");
> assertTrue(this.getClass().getEnclosingMethod() == null);
> assertTrue(this.getClass().getEnclosingMethod().getName() == null);
> return;
> }
> 
> logger.logp(Level.INFO, this.getClass().getName(),
> this.getClass().getEnclosingMethod().getName(),
> "No worries, I'm not lost");
> assertTrue(this.getClass().getEnclosingMethod() != null);
> assertTrue(this.getClass().getEnclosingMethod().getName() != null);
> 
> }
> }
> 


More information about the jdk-dev mailing list