How to solve “javax.naming.Reference cannot be cast to”

This article discusses how to solve the ClassCastException which can happen when you reference to external objects in the JNDI Tree.

Firstly, let’s check an example error message:
ClassCastException javax.naming.Reference cannot be cast to javax.jms.ConnectionFactory

In a nustshell, the javax.naming.Reference represents an object external to a naming system that is referred to by an object in the naming system. A Reference contains an address for retrieving the object from its naming system.

The address is a communications end point that enables JNDI to contact the object. The address can be any concrete subclass of RefAddr, such as a StringRefAddr for representing a URL or DNS name. A Reference also contains the class name of the referenced object.

Solving the ClassCastException error

This error typically happens when you are trying to lookup a component like a JMS ConnectionFactory or a Datasource from the JNDI. The most frequent reason is that you are missing some libraries in the classpath.

Therefore, check which is the resource that you are not able to cast. If it is a javax.jmx.ConnectionFactory, for example, you might need the JMS broker implementation in your classpath.

For example, if you are connecting to IBM MQ Broker, you might need in your classpath the Client libraries: