简体   繁体   中英

Java: Subclassing ResourceBundle

Say I have some instance of ResourceBundle:

ResourceBundle bundle = getBundle();
... 
    some more code that does stuff with bundle
...

I want to know if bundle has a particular key. Unfortunately, all of the methods I would use (containsKey(), keySet(), etc.) also check the parent bundle for the key. The method I would want to use is handleKeySet(), which is protected, therefore not visible.To get around this issue, the only solution I can think of is to create a subclass of ResourceBundle and implement getKeys() such that it returns only the keys of the current bundle and excludes the keys of the parent.The part where I start to doubt this solution is probably due to my confused understanding of inheritance. My question is.. does this seem to be the right way to go? And if so, any hints or a push in the right direction would be appreciated.

In theory, when you create a subclass you do not alter the behavior inheritated, what you do is "improve" it by making it more specific to your needs.

For example, you could extend GregorianCalendar into MyGregCal in order to use it to calculate the zodiacal sign corresponding to a given date. But you should avoid altering it in order to, say, calculate the julian calendar. Why? Because every method that accepts a GregorianCalendar will accept a MyGregCal, and will expect that it provides the functionality of GregorianCalendar. If it does not, then bad things (worse, unexpected bad things) can happen everywhere.

So, if you can not get the functionality that you need without breaking the contract of the parent class, you should look somewhere else. Write the class from scratch, or from a simpler parent class ( Properties ?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM