Home > Blockchain >  Access private logger in parent class
Access private logger in parent class

Time:07-20

I have the following class which I can't modify:

public class StorageRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(StorageRepository.class);

}

I have to use this class:

public class SecRepository extends StorageRepository {

   LOGGER.error(.....);

}

The parent class can't be modified because it it's in a private jar.

What are the options to solve the error: LOGGER' has private access in 'com.StorageRepository'

CodePudding user response:

If you really want to use the same Logger, just use

private static final Logger LOGGER = LoggerFactory.getLogger(StorageRepository.class);

in SecRepository, and it will retrieve the same Logger instance.

CodePudding user response:

You can achieve this using reflection:

public Logger getLogger() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
    Field f = StorageRepository.class.getDeclaredField("LOGGER");
    f.setAccessible(true);
    return (Logger) f.get(null);
}
  •  Tags:  
  • java
  • Related