Java Type Class Exception from String

George Hernando :

I have the following code snippet that I was trying to fix:

In a spring context file, there is a bean configuration, something like this:

<bean id="myBean"  >
    <property name="interface">
        <value>com.company.data.DataClass</value>
    </property>
</bean>

With a corresponding setter as follows:

public void setInterface(Class<?>[] interfaces)
{                               
    this.worker.setInterfaces(interfaces);  
}

This works when the class exists.
But in certain environments the class may not exist and then an error is thrown. Instead we'd like to handle the error when the Class isn't available.

I tried to fix the setter code as follows, but now it fails now when the Class actually does exist: java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Class

public void setInterface(Object interfaceTest)
{
    try
    {       
        Class<?>[] interfaces = (Class<?>[])interfaceTest);         
        this.worker.setInterfaces(interfaces);
    }
    catch(Exception ex)
    {           
        this.notValidInterface = true;
    }
}

I'm not sure why the handling here is different.

Karol Dowbecki :

Use String to define the value and Class.forName() to attempt to load the class checking if it exists.

<bean id="myBean">
  <property name="interface">
    <value>com.company.data.DataClass</value>
  </property>
</bean>
public void setInterface(String[] interfaces) { 
  List<Class<?>> cls = new ArrayList<>();
  for (String i : interfaces) {
    try {
      cls.add(Class.forName(i));
    } catch (ClassNotFoundException ex) {
      // handle the error
    }
  }                              
  this.worker.setInterfaces(cls.toArray());  
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=167068&siteId=1
Recommended