aspose file tools
The moose likes Java in General and the fly likes Classloader and casting, how to? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Classloader and casting, how to?" Watch "Classloader and casting, how to?" New topic

Classloader and casting, how to?

daniele licitra
Ranch Hand

Joined: Apr 08, 2013
Posts: 53

i've implemented the loading procedure has described in
This procedure works.

I've an abstract class AbstractModule that implement the interface ModuleInterface.
Now, I build some different class, Module1, Module2, ecc that extends AbstractModule.

I use this function to load and instantiate the class:

In the core of the program i use

where modulo is of type AbstractModule.
The problem is in the row signed by the arrow or in the calling of the loader over there, i recive the exception:

SEVERE: java.lang.ClassCastException: com.bss.framework.bssmoduloutenti.ModuloGrafico cannot be cast to com.bss.framework.astratte.AbstractModule
at com.bss.framework.utils.BssLoader.caricaModulo( <-- this is the arrowed key
at com.bss.framework.servizi.SessioneUtente.setModuloCorrente( <--- this is the calling

How can I solve it? There is something wrong?

JPA 2.1.0
Glassfish 3.1->4, Wildfly, Primefaces 3.4->4
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14665

First of all, does com.bss.framework.bssmoduloutenti.ModuloGrafico indeed extend com.bss.framework.astratte.AbstractModule?

Furthermore, the problem might be that you load the ModuloGrafico class using another classloader than what AbstractModule was loaded with. I don't know the exact details, but as far as I know classloaders are separated in such a way that a class loaded with one classloader is in a separate space than classes loaded with a different classloader.

It's just a guess and I'm not sure if it will work, but I think it might work if you initialize your URLClassLoader differently, setting the classloader of AbstraceModule as the parent:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
daniele licitra
Ranch Hand

Joined: Apr 08, 2013
Posts: 53

Thank for replying.

i've modified the loader function according to yout reply:

i send the Classloader c from the caller and it works! Thanks a lot
I agree. Here's the link:
subject: Classloader and casting, how to?