-1

i cannot access a protected method in a subclass (in same package).

I am using spring-jms API's , DefaultMessageListenerContainer class.

In my code, i have an instance of DefaultMessageListenerContainer class, and i am trying to invoke getBeanName() method on that object, but in eclipse it says,

"The method getBeanName() from the type AbstractJmsListeningContainer is not visible"

As per javadoc ,this getBeanName() method is a protected method defined in superclass, 'AbstractJmsListeningContainer'.

Per my understanding, we should be able to access protected method inside subclass. Am i missing something ?

Attaching a sample java code snippet.

enter image description here

vishy
  • 483
  • 2
  • 7
  • 16
  • 1
    Don't post pictures. Show us where you're trying to use the code you've shown. – Sotirios Delimanolis Aug 11 '15 at 21:04
  • I do not fully understand your situation; I cannot open your picture in my browser sorry. Could you please answer these questions: 1. Is DefaultMessagListenerContainer from the API you are using or it it your subclass? 2. Are you subclassing DefaultMessageListenerContainer? If so you cannot access the protected member because you can only access protected members if they your class is a direct subclass of the superclass – univise Aug 11 '15 at 21:07
  • I posted the picture to illustrate the issue. – vishy Aug 11 '15 at 21:07
  • @univise : 1. Yes 2. No i am not subclassing – vishy Aug 11 '15 at 21:08
  • Below is my code snippet, – vishy Aug 11 '15 at 21:09
  • for(DefaultMessageListenerContainer container:containers){ //stop container, if its running if(container.isRunning()){ logger.warn("Container "+container.getBeanName() + "' was up.Bringing it down."); container.stop(); } } – vishy Aug 11 '15 at 21:09
  • I see there is a new answer which is correct. You can access protected member only if 1. your are directly subclassing it 2. your class is in the same package. I assume your class is not in the same package? – univise Aug 11 '15 at 21:10
  • No. Edit your question and add it there. _we should be able to access protected method inside subclass._ Which subclass? Where do you have a subclass? – Sotirios Delimanolis Aug 11 '15 at 21:11

1 Answers1

2

The code fragment you posted is not accessing getBeanName() from within the subclass. It is trying to access it from client code. You'd have to define your own subclass to expose a public method to get to it:

class MyDefaultMessageListenerContainer extends DefaultMessageListenerContainer {
    public getMyBeanName() { return getBeanName(); }
}

MyDefaultMessageListenerContainer container = new MyDefaultMessageListenerContainer();
String name = container.getMyBeanName();

Note that you can't simply override getBeanName() because it is declared final.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521