Casting to an abstract class from a different classloader

I have a class Special that extends an abstract class Base. In my code I use a URLClassLoader to load the class Special and I then want to cast Special to Base. If I do this I get a ClassCastException because the classes are loaded from different classloaders. I can't have the URLClassLoader and the class that performs the cast extend a parent ClassLoader that knows about the Base class. What I want to be able to do is something like this:
URLClassLoader loader = new URLClassLoader(codebase, null);
Class baseClass = loader.loadClass(className);
Base baseObj = (Base)baseClass.newInstance();
I have seen some post that suggest I can achieve this using Reflection but I am not sure how to go about this. Any help would be appreciated.
Thanks
Jim.

Thanks for your help so far but I still can't do the casting, consider this example:
//Base.java
package classTest;
public interface Base
     public abstract void execute();
//ConcBase.java
package classTest;
public class ConcBase implements Base
     public void execute()
          System.out.println("execute in ConcBase called");
I compile these files and jar them into work.jar
I now have my application:
//Test.java
import java.net.*;
import java.io.*;
import classTest.*;
public class Test
public static void main(String[] args)
          Test t = new Test();
          t.test();
     public void test()
          try
               File file = new File("D:/Projects/classloadTest/work.jar");
               URL[] codebase = {file.toURL()};
               ClassLoader ccl = getClass().getClassLoader();
               ccl.loadClass("classTest.Base");
               URLClassLoader ucl = new URLClassLoader(codebase,ccl);
               Class conClass = ucl.loadClass("classTest.ConcBase");
               classTest.Base b = (classTest.Base)conClass.newInstance();
               b.execute();
          catch(Exception t)
               System.out.println("thowable caught");
               t.printStackTrace(System.out);
I compile this and run it with this command:
java -classpath D:\Projects\classloadTest\work.jar;. Test
This runs as I would expect, however I have set the parent class loader of my custom URLClassLoader to the one that does the cast, this means that Base and ConcBase are both being picked up by the application class loader as my custom class loader delegates to its parent. This is the current behaviour I have in my proper application and it is causing problems, I don't want the class that implements Base to delegate to any class on the main applications classpath. If I change the line:
URLClassLoader ucl = new URLClassLoader(codebase,ccl);
In Test.java to:
URLClassLoader ucl = new URLClassLoader(codebase,null);
I get a ClassCastException, this is because the class that does the cast (Test) loads Base from it's classpath and ConcBase is loaded from the URLClassLoader. After spending more time looking at this problem I don't think there is anyway to resolve but if anyone thinks there is please tell me.
Many thanks
Jim.

Similar Messages

  • Invoke a method in one class from a different class

    I am working on a much larger project, but to keep this simple, I wrote out a little test that would convey the over all theory of the program.
    What I am doing is starting out with a 2 JFrames and a Class. When the program is launched, the first JFrame opens. In this JFrame is a label and a button. When the button is clicked, the second JFrame opens. This JFrame has a textField and a button. The user puts the text in the textField and presses the button. When the button is pushed, I want the text that was just put in the textField, to be displayed in the first JFrame's label. I am trying to invoke a method in the first JFrame from the second, but nothing happens. I have also tried making the Class extend from JFrame1 and invoke it from there, but no luck. So, how do I invoke a method in a class from a different class?
    JFrame1 (I omitted the layout part. I made this in Netbeans so its pretty long)
    public class NewJFrame1 extends javax.swing.JFrame {
         private NewClass1 nC = new NewClass1();
         /** Creates new form NewJFrame1 */
         public NewJFrame1() {
              initComponents();
              jLabel1.setText("Chuck");
         public void setLabels()
              jLabel1.setText(nC.getName());
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
         NewJFrame2 j2 = new NewJFrame2();
         j2.setVisible(true);The class
    public class NewClass1 {
         public static String name;
         public NewClass1()
         public NewClass1(String n)
              name = n;
         public String getName()
              return name;
         public void setName(String n)
              name = n;
    }The second jFrame
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
         NewClass1 nC = new NewClass1();
         NewJFrame1 nF = new NewJFrame1();     
         nC.setName(jTextField1.getText());
         nF.setLabels();
         System.out.println(nC.getName());At this point I am begging for help. I have been trying for days to figure this out, and I just feel like I am not getting anywhere.
    Thanks

    So, how do I invoke a method in a class from a different class?Demo:
    public class Main {
        public static void main(String [] args) {
         Test1 t1 = new Test1();
         Test2 t2 = new Test2();
         int i = t1.method1();
         String s = t2.method2(i);
         System.out.println(s);
    class Test1 {
        public int method1() {
         return 10;
    class Test2 {
        public String method2(int i) {
         if (i == 10)
             return "ten";
         else
             return "nothing";
    }Output is "ten".
    Edited by: newark on May 28, 2008 10:55 AM

  • Extend abstract class & implement interface, different return type methods

    abstract class X
    public abstract String method();
    interface Y
    public void method();
    class Z extends X implements Y
      // Compiler error, If I don't implement both methods
      // If I implement only one method, compiler error is thrown for not
      // implementing another method
      // If I implement both the methods,duplicate method error is thrown by 
      //compiler
    The same problem can occur if both methods throw different checked exceptions,or if access modifiers are different..etc
    I'm preparing for SCJP, So just had this weired thought. Please let me know
    if there is a way to solve this.

    Nothing you can do about it except for changing the design.
    Kaj

  • How to instantiate a class from a different package?

    I am trying to instatiate a class in a package: a.b.c from another class in a different package: d.e.f
    How could I do so?
    I've already been trying many things but didn't manage to get it to work...

    Did you include both jar files in your classpath? Use
    the -cp option of the java interpreter to specify your
    classpath.Well, I tried adding the jar file to the classpath, without any success...
    String path = getClass().getProtectionDomain().getCodeSource().getLocation().toString();
                   String finpath = "";
                   for(int i=6;i<path.length();i++)
                        finpath = finpath+path.charAt(i);
                   System.setProperty("java.class.path",System.getProperty("java.class.path")+";"+finpath+"mm.mysql-2.0.14-bin.jar/");That's what I did and it didn't work...
    If you "unpack" the jars see if there is the correct
    packages-folders symmetry...Yes, the classes are in the package-folders they should be in..

  • Accesing a class from a different PC on Internet

    Hi all. I have the following problem:
    I have a Java programa that access to serial port to send data to a device. It works good.
    Also I have Jakarta Tomcat installed, and a servlet that instantiate the previous java program that access to serial port.
    If this PC is connected directly to Internet, there are no problems to people from Internet can send data to serial port.
    But I would like to put the device connected to another computer not connected directly to Internet.
    I know Jakarta Topmcat should be on the PC connected directly to Internet, but...are there any possibility that my servlet call my Java serial port programme on a different computer ? E.g: using a special nomination before the class name...Also someone told I should use Java RMI...Dont know if its very difficult to use...
    Would appreciate some advice or example code...
    Thanks...
    John

    RMI seems to be a perfect solution to your problem. It isn't difficult to use, but will involve a little learning. It's a cool technology though, and should be fun to mess around with.
    To learn it go to http://java.sun.com/docs/books/tutorial/rmi/index.html
    The example that they use is cool, it's where I learned it first.
    Dave

  • Instanciate a class from a different sector

    I have a structure on my server like this :
    BO
    /|\
    / | \
    / | \
    A B C
    BO : My Business Objects (EJB)
    A,B,C : my different Web Applications (separated)
    How shall i have to do for instanciating in my Web application A a class of my Web application B ?
    Thanks a lot.

    Include in the WAR file of webapp A the *.class file of webapp B that you want to instantiate in webapp A, or put the *.class in someplace where the container will look for *.class files.
    Jesper

  • EJB lookup returned stub from a different classloader.

    I've written an EJB for doing authenitcation. This EJB is accessed by an security-mbean (BEA's login module).
    - The EJB is deployed in an EAR.
    - The EJB-stubs are extracted and is included as part of the MBEAN Jar.
    When I hit a webapp causing the EJB lookup to occur, the stub object returned is created by the webapp's classloader. This cause a ClassCastException when trying to cast the returned home interface into the home interface of the MBEAN's classloader.
    Note that all this is happening on the same BEA server running WLS8.1.
    I don't want to put the EJB jar on the system classpath so I can redeploy the EJB, the Application's EAR and the MBEAN to a cluster.
    -alex

    Robert Greig <[email protected]> wrote:
    Thanks for responding to my question, which newsgroup is more appropriate for
    my line of question?
    But before I move this thread, I would like to add:
    I've already handled the recursion problem on top of the ejb-lookup before JNDI
    becomes avaliable (while doing server startup) problem.
    The advantage with the EJB model is this. By changing the host/port configuration,
    I can switch between a local-authentication server or a remote provide authentication
    server network configuration.
    If I were to include the necessary classes in the mbean JAR from our application,
    there maybe resources issues since I now have 2 classloaders loading my server-portion
    of classes. Not sure how that will workout with resources and all. This model
    has the disadvantage of any classes I have in the mbean JAR will require updates
    outside my EAR. This wroks against the EAR deployment model.
    -alex
    Alex Cheung wrote:
    I've written an EJB for doing authenitcation. This EJB is accessedby an security-mbean (BEA's login module).
    - The EJB is deployed in an EAR.
    - The EJB-stubs are extracted and is included as part of the MBEANJar.
    This isn't a good approach. You are pretty much stuffed mainly for the
    reasons you outline.
    Also note that if you continue to go down this road you will have to
    handle the potential recursion (i.e accessing an EJB will invoke a
    security call to your provider!).
    Why do you need to implement this as an EJB? The main advantages of EJBs
    are security and container managed transactions neither of which is
    relevant here surely?
    Robert

  • Importing class from different directory

    Hi, Can anyone tell me how to import a class from a different directory? I have a DGenerator class in ./generator directory.
    I have tried Import generator.DGenerator; to use the DGenerator class. However. I got the error:
    cannot access generator.DGenerator
    bad class file: ./generator/DGenerator.class
    class file contains wrong class: DGenerator
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    Help please.
    Thank you!

    I don't understand why this is a Swing question, but at any rate if you want your DGenerator class to be found in a particular directory, you must do one of two things:
    1. Put that directory in your classpath and just refer to the class as DGenerator.
    2. Make the class belong to the package "generator".

  • From abstract class to public class

    I am developing a editor base application...wondering that how to cancel the abstract class and put all the abstract class methods into the public class..?? thanks

    Is this a C++ question? If so, you should post it in the C++ forum. If it is a Java question, post in the Java forum.
    In either case, please make your question more specific. It sounds like all you have to do is copy the functions from the abstract class to the derived class, remove the dependency on the abstract class, and delete the abstract class from the source code. Presumably that is not what you are asking.

  • Abstract class - subclass

    a quik question: if I have a abstract class define a method, and a subclass implementing it, and a third class with an instance casted as the abstract class, would the following method in the subclass then return the instance casted as subclass? :
    public Subclass getInstance() {
    return this;
    Stig.

    oops.... cant return SubClass....

  • Abstract class not visibe

    I have written and tested an abstract-class inside a project. Now i moved the abstract class from my project to utility.jar Ten I added this utility.jar to my classpath. Using eclipse as my application devtool, i can see that the class is availabe in the jar (so far so good).
    But, when i add the import-statement to use the class in my current project, i get an error that the class is not visible.
    any leads?

    Praveen_Forum wrote:
    -Kayaman- wrote:
    Your abstract class isn't a public class?
    Basics, basics...we can't make abstract class private can we??I was thinking more default, i.e. package private.

  • EJBs accessing protected classes from java classloader

    Hello,
    We are facing a problem with classes isolation. I read from this newsgroup that
    to access a package level class from the base classloader from a bean, the supporting
    classes has to be from the same classloader as the bean. Well I think the only
    way we could do that is to have the *Bean.class in the base classloader, which
    is not what's recommended or move the support classes into the bean's classloader,
    which we cannot do.
    The purpose of this mail is to ask: is it a bug from weblogic server? Will it
    be fixed one day? If not, does it mean that it is impossible to isolate classes
    for local access from public classes?
    Thank you, Khiet.

    Thank you for your reply.
    Hope that one day we will not be obliged to have anything in the main classpath.
    :) Khiet.
    Rob Woollen <[email protected]> wrote:
    Tran T. Khiet wrote:
    Hello,
    We are facing a problem with classes isolation. I read from this newsgroupthat
    to access a package level class from the base classloader from a bean,the supporting
    classes has to be from the same classloader as the bean. Well I thinkthe only
    way we could do that is to have the *Bean.class in the base classloader,which
    is not what's recommended or move the support classes into the bean'sclassloader,
    which we cannot do.All correct.
    The purpose of this mail is to ask: is it a bug from weblogic server?No, it's how java classloaders work.
    Will it
    be fixed one day? If not, does it mean that it is impossible to isolateclasses
    for local access from public classes?You can expect that future versions of WLS will allow the user more
    control over classloaders, but for now you'll need public or protected
    access to cross classloaders.
    -- Rob
    Thank you, Khiet.

  • Classes which inherited from the same abstract class calling each other

    I have a design that contains such classes.
    1) Media - defines some methods to get data which business logic wants and some others to deal with data
    media.java
    public abstract class Media {
       public abstract Object getSomeData(String type);
       public void methodForMedia() {
           // do something here...
    }And certainly, a lot of classes derive from it to function differently.
    etc,
    DynamicMedia.java
    public class DynamicMedia extends Media {
       public Object getSomeData(String type) {
          // get some data here...
          return somedata;
       public void methodForMedia() {
           // inherits and overrides here
       public void methodForDynamicMedia(String data1, Object data2) {
           // do something here...
    }FixedMedia.java
    public class FixedMedia extends Media {
       public Object getSomeData(String type) {
          // get some data here...
          return somedata;
       public void methodForMedia() {
           // inherits and overrides here
       public Object getFixedMediaData(String type) {
           // get some fixed data here
           return someFixedData;
    }2) Business - which implements business logic
    public class Business {
         public void transactionOne() {
               FixedMedia fm = getMedia(FixedMedia.class);
               Object fixedData = fm.getFixedMediaData("fixedDataType");
               DynamicMedia dm = getMedia(DynamicMedia.class);
               dm.methodForDynamicMedia("somedata", fixedData);
    }Calling methods defined in DynamicMedia might need
    many data that can only be retrieved through FixedMedia
    (or any similar class just as FixedMedia - derived from Media and handle "fixed" data).
    So we decide to define a field to contain a reference of FixedMedia or its container (a list, map)
    in DynamicMedia to reduce the codes.
    But it results the coupling between DynamicMedia and FixedMedia(s).
    Which design is better on testing, quality?

    Why not just use an interface?
    And why does methodForDynamicMedia() exist only there?
    So we decide to define a field to contain a reference of FixedMedia or its container (a list, map)
    in DynamicMedia to reduce the codes.Sounds like a muddled design. Sometimes you might make an implementation decision that adversely impacts the design but you better have a better reason than just because it reduces some code. Maybe it reduces a lot of code, but if so then that might suggest something is wrong with the design.

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

Maybe you are looking for

  • How to restrict number of rows display using ig:gridView

    Hi All How to restrict number of rows display using <ig:gridView datasource="{mybean.mylist}"> i am getting 10 rows using data_row . i wanna show only first 5 rows . pageSize ="5" will be ok . but it displays remaining rows in next page. but i want t

  • How do I link clips in the timeline so that they move together?

    I cannot seem to effectively link my clips together in the timeline and it is causing me multiple problems. First of all, when I want to move a clip from one place to another, the other clips after it are not moving forward to close the gap. I tried

  • Where are all the "DCIM" folders on iPhone?  Everything not in Camera Roll.

    I just finished stripping down all the DCIM folders accessible from a PC via Windows Explorer.  I'm really looking for answers on the "how to", not "why it is" or "it just is that way" please. The DCIM folders (mine [iPhone 5 w iOS 7.x] shows 5, nami

  • Problem about Reporting Model-layer Warnings to JSF

    hi, I have read not document article "Reporting Model-layer Warnings and Informational Messages to JSF [10.1.3.1]" the address is :http://radio.weblogs.com/0118231/stories/2004/09/23/notYetDocumentedAdfSampleApplications.html#101 and do it as it desc

  • Electronic Signature Recommendations

    My department is currently looking at accepting e-signatures on our contracts.  However, we would like the signature to actually look like a wet signature, not just a typed name, we would also like some sort of validation that the name on the form is