How to load parent Class like this?

I have a java application that use another class in a jar file. And there is a class in the application's main class extends the class in the jar file. I have packaged the application into a jar file.
the directory structure :
foder [dist] : app.jar [lib]
foder [lib]: Library.jar
(I excute "java" cmd in folder "dist" )
Now i can run it, if i use command line option -Xbootclasspath/a:
"java -Xbootclasspath/a:lib/lib.jar -jar app.jar"
(Because if i use "java -jar ", "-cp .;lib/Library.jar" option have no effect.)
But I don't konw how make it run by codes.I tried this:
Main.javapackage myapp;
java.net.URL liburl = new java.io.File("lib\\Library.jar").toURL();
java.net.URLClassLoader loader =
        new java.net.URLClassLoader(new java.net.URL[] { liburl });
Class c = loader.loadClass("mylib.parentclass");
Object    parentobj = c.newInstance();
//c = loader.loadClass("myapp.subclass");  //can't run
//Object    subobj  = c.newInstance();
subclass.javapackage myapp;
subclass extends parentclass{
}parentclass.javapackage mylib;
public class  parentclass{
}the code Object    parentobj = c.newInstance(); can excute without problem . parentclass's constructor excuted.
but
c = loader.loadClass("myapp.subclass");
Object    subobj  = c.newInstance();can not excute and without any exception throw out.
I used the "-verbose:class" option , the output is:
[Loaded java.lang.ClassFormatError from shared objects file] <---the last line
Thanks for reading and participating .
Please help me or point me to resources where I can read .
Sorry for my poor english.
thanks a lot .

The problem is that when a class wants to resolve a reference to another class (e.g. when a class fetches it's parent) it uses the classloader that loaded it, which is not necessarilly the classloader from which it was requested.
When you ask a standard classloader (e.g. URLClassLoader) for a class the first thing it tries is asking it's parent class loader. Only if the parent doesn't find the class does it try itself.
So, if a class is available to the system ClassLoader then even though you ask a URLClassLoader for it, it's the system ClassLoader which actually loads it and, hence, it's the system ClassLoader that class uses to resolve any references.
ClassLoaders generally form a kind or heirarchy and references can be made towards the root of the ClassLoader tree, but not in the other direction.
You would have to do something like have a small main class which sets up the classloader and make your real main class available only on the jars that the URLClassLoader adds to the classpath. That way the main class will have the URLClassLoader as its ClassLoader and will use it to get it's parent class.

Similar Messages

  • How can i generate xml like this?

    Hi all,
    How can i generate xml like this & i need to send it to via HTTP :
    <mms>
                 <subject>message subject</subject>
                 <url_image>http://image_url</url_image>
                 <url_sound>http://sound_url</url_sound>
                 <url_video>http://video_url</url_video>
                 <text>message text</text>
                 <msisdn_sender>6281XYYYYYY</msisdn_sender>
                 <msisdn_receipient>6281XYYYYYY</msisdn_receipient>
                 <sid>to be define later</sid>
                 <trx_id>Unique number</trx_id>
                 <trx_date>yyyyMMddHHmmss</trx_date>
                 <contentid>see note</contentid>
    </mms>& how can i get the value of the sid (for example)?
    I hav tried to generate that xml by using StringBuffer & append, but it's not what i mean...
    Anyone can help me?

    Ok...i got it. But i still hav some problems.
    This is the sample code that i used :
    public class XMLCreator {
         //No generics
         List myData;
         Document dom;
            Element rootEle, mmsEle, mmsE;
            StringWriter stringOut;
            mms mms;
         public XMLCreator(String subject, String image, String sound,
                    String video, String text, String sender, String recipient,
                    int id, String date, String contentid) {
              mms = new mms(subject, image, sound, video, text, sender,
                            recipient, id, contentid, date);
                    createDocument();
         public void run(){
              createDOMTree();
              print();
         private void createDocument() {
              //get an instance of factory
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              try {
              //get an instance of builder
              DocumentBuilder db = dbf.newDocumentBuilder();
              //create an instance of DOM
              dom = db.newDocument();
              }catch(ParserConfigurationException pce) {
                   //dump it
                   System.out.println("Error while trying to instantiate DocumentBuilder " + pce);
         private void createDOMTree(){
              //create the root element <Mms>
              rootEle = dom.createElement("mms");
              dom.appendChild(rootEle);
              createMmsElement(mms);
         private Element createMmsElement(mms b){
              Element subjectEle = dom.createElement("subject");
              Text subjectText = dom.createTextNode(b.getSubject());
              subjectEle.appendChild(subjectText);
              rootEle.appendChild(subjectEle);
              //create url_image element and author text node and attach it to mmsElement
              Element imageEle = dom.createElement("url_image");
              Text imageText = dom.createTextNode(b.getUrl_image());
              imageEle.appendChild(imageText);
              rootEle.appendChild(imageEle);
              // & etc....
              return rootEle;
          * This method uses Xerces specific classes
          * prints the XML document to file.
         private void print(){
              try
                   //print
                   OutputFormat format = new OutputFormat(dom);
                   format.setIndenting(true);
                            stringOut = new StringWriter();
                   //to generate output to console use this serializer
                   XMLSerializer serializer = new XMLSerializer(stringOut, format);
                   //to generate a file output use fileoutputstream instead of system.out
                   //XMLSerializer serializer = new XMLSerializer(
                   //new FileOutputStream(new File("mms.xml")), format);
                   serializer.serialize(dom);
              } catch(IOException ie) {
                  ie.printStackTrace();
            public String getStringOut() {
                return stringOut.toString();
    }when i tried to show the stringOut.toString() in my jsp, it's only showed string like this :
    The Lords Of The Ring http://localhost:8084/movie/lotr.3gp 6281321488448 6281321488448 123 0 20070220114851 LOTR.
    1. Why this is happen?i want to generate xml which its format is like above.
    2. How can i send this xml (put in msg parameter) using jsp (via web) without creating the mms.xml?
    3. if i want to set the msg parameter equal to mms.xml - means that msg = mms.xml, what is the data type for msg? is it an object or anything else?
    Thx b4 in advance...

  • I was downloading the software update for ipod touch 2gen and after it was done downloading it showed that there was an error with my ipod and when i saw it was on the lockscreen loading. its been like this for 4 hours already

    I was downloading the software update for ipod touch 2gen and after it was done downloading it showed that there was an error with my ipod and when i saw it was on the lockscreen loading. its been like this for 4 hours already

    What did the error message say?
    Try:
    - iOS: Not responding or does not turn on
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try on another computer                            
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
      Apple Retail Store - Genius Bar

  • How to Load a class manually

    Hello Friends,
    I need a help regarding how to load a class manually.
    i have the class name -- TestClass1
    and Path - com.apps.classes
    Thank you

    Thank You------
    I got the result
    String classPath = com.apps.className;
    Object obj = Class.forName(classPath).newInstance();

  • How to load java class from jsp page?

    hi all!
    Does anyone know how to load java class from jsp page?
    I try to load java class from jsp page.
    Is it possible to load java class fom jsp page?
    thanks and have a good day!

    What I mean is How to load/open java class file from jsp page?
    I think we can open Applet from jsp page by using
    <applet code=helloApplet.class width=100 height=100>
    </applet>
    but, how to open java class which is an application made by Frame?
    thanks and have a good day

  • How to make an avatar like this,

    Hello Adobe Community, i'm new here, i have a big question. I want to know HOW to make an avatar like this:
    I want to know how to do that effect that who zoom in and zoom out etc. WITHOUT SNOWING, only that effect, if you can help me please!
    That zoom effect is AWESOME... send me a tutorial please!

    I thought you said you knew how to make animated gif.  A frame is the composite of the layers that have their visibility on for the frame a frame may be made using many layers. You use tools and filters on layers.You make frame using layers.
    Photoshop also supports any size layer. Layers can be  larger the canvas size can have image data out side the canvas.  Layer image data position above can be move relative to the canvas.  The Cloud logo animation has two layer one is masked is masked the mask is not linked to the layers image data it stationary over the canvas and is more on less a masks more foe the background canvas then the layer its on. The layer it is on image data is more off canvas then over canvas. Photoshop also notes layer position in a frame information, A layer potion can be change from frame to frame. I only create two frame for that animation.  The first and last frame, The first frame I had the top late image JJMACK high and off canvas to the left.  The last frame had it low and off canvas to the right. I then had Photoshop generate 138 frames between the two frames I created.  So Photoshop moved the top layer position across the canvas  left to right and high to low direction and the stationary layer mask masked it as if it were going through the background layers clouds.  The two layers are visible in all frames.

  • How Could I Make Something Like This.

    http://www.youtube.com/watch?v=vlRdjAwEzbU
    I Am Wondering How I could make something like this in AfterEffects CS4.
    Any Help Would Be Appreciated.

    dx394 wrote:
    Is There A Tutorial Anywhere About It?
    You could contact the animator or whoever posted the clip.
    Deconstruct the sequence. observe the moves and decide, with your present level of familiarity, how you would approach it. Scaling of the ten or so different layers is simple enough but acquiring the contents of the layers is not something you will do in AE.
    As Todd says, start small, figure it out one step at a time, move on to more advanced functions. Animting 3D layers is 9 times more difficult than 2D. when you add lighting and camera moves you raise the complexity level and rendering time to another power making your project about 27 times more difficult.
    bogiesan

  • I was wondering how you would do something like this?

    Hi i was wondering how you would do something like this?
    i recently got photshop CS5 and wanted to do something like this!

    Not sure exactly what the effect you are looking at, but my first glance is just an overly of 3 or more pictures.  The portrait in the back is just like 50% transparency.

  • HT201441 I found a phone that had been stolen, so I asked apple id to its original owner she said that she had forgotten and replace the apple id, how to solve a problem like this?

    II found a phone that had been stolen, so I asked apple id to its original owner she said that she had forgotten and replace the apple id, how to solve a problem like this?

    Send the original owner this link.
    (120249)

  • How to load CAD files like .prt, . stp  in JAVA

    How to load CAD files like .prt, . stp files which can be generated by UG and Pro/E etc in JAVA. I am appreciated that you will give any comments.

    Hi,
    as far as I know there is no Java 3D loader for CAD files available. You have to export your files into a format like "3ds ", "obj ", or "wrl". See thread 'JAVA 3D max files and VrmlLoader' on java.net: [http://forums.java.net/jive/thread.jspa?messageID=231564&#231564|http://forums.java.net/jive/thread.jspa?messageID=231564&#231564]
    August

  • How to load a class dynamically (via reflection) in a jsf-component

    Hi all,
    I am writing my own jsf component and I would like to do it generically. Therefore I have an attribute, where the developer can pass a fully qualified classname, which I want to use to instantiate. But I have a Problem with the classloaders, everytime I get a ClassNotFound-Exception during debugging.
    Does anybody know how it is possible, to to get the most parent classloader?
    Currently I am even not able to load a class, which is in the same package like all other compontent-classes.
    Thank you very much in advance
    Thomas

    Within web applications, I believe it is recommended to use Thread.getContextClassLoader(). Keep in mind that web applications require different classloader semantics than regular Java applications. The class loader which gets resources from the WAR is favored over others, even when this violates the normal class loading conventions.

  • How to load a Class Dynamically?

    hi,
    I have the following problem.I am trying to load a class dynamically.For this I am using ClassLoader and its Loadclass method.My code is like this,
    File file = filechooser.getSelectedFile();
    ClassLoader Cload = this.getClass().getClassLoader();
    String tempClsname= file.getName();
    Class cd =Cload.loadClass(tempClsname);
    Object ob =(Object)cd.newInstance();
    showMethods(ob);
    In showMethods what i am doing is getting the public methods of the dynamically loaded class,
    void showMethods(Object o){
    Class c = o.getClass();
    System.out.println(c.getName());
    vecList = new Vector();
    Method theMethods[] = c.getDeclaredMethods();
    for (int i = 0; i < theMethods.length; i++) {
    if(theMethods.getModifiers()==java.lang.reflect.Modifier.PUBLIC)
    String methodString = theMethods.getName();
    System.out.println(methodString);
    vecList.addElement(methodString);
    allmthdlst.setListData(vecList);
    Now whenever i work with this i m getting a runtime error of CLASS NOT FOUND Exception..I know its because of Classpath..But i don't know how to resolve it??pls help me in this regard...
    Also previously this code was working with java files in the directory in which this java file was present..How to make it work for java file in some other directory..pls help me in this regard...
    Thanks in advance..

    You sure didn't need to post this twice.
    http://forum.java.sun.com/thread.jsp?thread=522234&forum=31&message=2498659
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].
    You resolve this problem by ensuring the class is in the classpath and you refer to it by its full name.
    &#167;

  • How to Load a class file base on .class file name???

    Hi,
    Can anyone help me?
    1) Based on filename (d:\temp\bla.class), I want to load this bla.class and get the actual package of this class.
    example:
    package something.temp;
    public class bla
    I want to load the file base on filename and get the package of the class. Is it possible ?
    Thank you.

    Hi nikki96,
    It will not work. I will get java.lang.NoClassDefFoundError eventhough I extends classloader to use the findClass(String filename);
    Example:
    import java.security.*;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.jar.Attributes;
    import java.util.jar.Manifest;
    import sun.misc.Resource;
    import sun.misc.URLClassPath;
    public class MyURLClassLoader extends ClassLoader
    String host;
    int port;
    public Class findClass(String name)
                   try
         byte[] b = loadClassData(name);
         return defineClass(name, b, 0, b.length);
                   } catch(Exception e)
                        e.printStackTrace();
                   return null;
    private byte[] loadClassData(String name) throws Exception
                   // load the class data from the connection
                   File file = new File(name);
                   InputStream is = new FileInputStream(file);
                   long length = file.length();
                   // You cannot create an array using a long type.
                   // It needs to be an int type.
                   // Before converting to an int type, check
                   // to ensure that file is not larger than Integer.MAX_VALUE.
                   if (length > Integer.MAX_VALUE) {
                        // File is too large
                   // Create the byte array to hold the data
                   byte[] bytes = new byte[(int)length];
                   // Read in the bytes
                   int offset = 0;
                   int numRead = 0;
                   while (offset < bytes.length
                        && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                        offset += numRead;
                   // Ensure all the bytes have been read in
                   if (offset < bytes.length) {
                        throw new IOException("Could not completely read file "+file.getName());
                   // Close the input stream and return bytes
                   is.close();
                   return bytes;
    Problem: The class file is not in the proper package (d:\temp\bla.class) where the proper package is d:\something\temp\bla.class.
    Objective: I just want to base on the bla.class (no matter where is it located), then get the package of the classfile (bla.class) like example something.temp.
    Simple as that but I don't know how to do :(.

  • How to load a .class file dynamically?

    Hello World ;)
    Does anyone know, how I can create an object of a class, that was compiled during the runtime?
    The facts:
    - The user puts a grammar in. Saved to file. ANTLR generates Scanner and Parser (Java Code .java)
    - I compile these file, so XYScanner.class and XYParser.class are available.
    - Now I want to create an object of XYScanner (the classnames are not fixed, but I know the filename). I tried to call the constructor of XYScanner (using reflection) but nothing works and now I am really despaired!
    Isn't there any way to instantiate the class in a way like
    Class c = Class.forName("/home/mark/XYScanner");
    c scan = new c("input.txt");
    The normal call would be:
    XYLexer lex = new XYLexer(new ANTLRFileStream("input.txt"));The problem using reflection is now that the parameter is a ANTLRFileStream, not only an Integer, as in this example shown:
    Class cls = Class.forName("method2");
    Class partypes[] = new Class[2];
    partypes[0] = Integer.TYPE;
    partypes[1] = Integer.TYPE;
    Method meth = cls.getMethod("add", partypes);
    method2 methobj = new method2();
    Object arglist[] = new Object[2];
    arglist[0] = new Integer(37);
    arglist[1] = new Integer(47);
    Object retobj = meth.invoke(methobj, arglist);
    Integer retval = (Integer)retobj;
    System.out.println(retval.intValue());Has anyone an idea? Thanks for each comment in advance!!!

    Dump all of your class files into a directory.
    Use the File class to list all files and iterateover
    the files.NastyNot really, when you are dynamically creating code, I would expect the output to be centralized, not spread out all over the place.
    >
    Use a URLClassloader to load the URL that isobtained
    for each file with file.toURI().toURL()(file.toURL()
    is depricated in 1.6)Wrong, the URL you give it must be that of the
    directory, not the class file.No, I did this quite recently, you can give it a specific class file to load.
    >
    Load all of the classes in this directory, thatway
    any anonymous classes are loaded as well.Anonymous classes automatically loaded when the real
    one isIt can't load it if it doesn't know where the code is. Since you haven't used a URL classloader to load once class file at a time, you would never encounter this. But if you loaded a class file that had an anonymous classfile it needed, would it know where to look for it?
    >
    From this point you should be able to just get a
    class with Class.forName(name)No. Class.forName uses the classloader of the class
    it's called in, which will be the system classloader.
    It won't find classes loaded by a URLClassLoader.got me there.

  • How to load a class in lib/file.jar

    Hi,
    I use jboss 4.0.2. and i have a jar-file from a third party in my server/default/lib that calls Thread.currentThread().getContextClassLoader().loadClass("foo"); My problem is that foo.class is never found and i dont know where i have to place this class. I would like to have a seperate folder for my classes, but i dont know how i should configure the classloader to find my classes. i dont want to package them in a jar.
    Thanks a lot!

    i tried this but the class was not found
    my simple question is:
    if a class in a jar that is placed in my jboss/server/default/lib-directory tries to load a class dynamic, where is it(classloader) looking? please tell me...
    thanks

Maybe you are looking for

  • Business Rules Instance disappeard in projects folder in Shared Services

    Hi all, I have this strange thing happend to me today morning. when i logged into the Shared Services i can find the Business Rules folder but i couldnt find the instance for it.Is there any way i can reconfigure it so that i can see the instance bac

  • Po Printing Report

    Hi I am working on PO Printing Report.There are mainly three section .1 is Header part which contains informaition like Bill to Address Ship to address,vendor address payment terms etc,middle part contais lots of information like header notes,supplie

  • Tax code wise balances in different G/L accounts

    Dear All My customer requires a report where he can see tax code wise balances that can exist in different G/L accounts. In the input screen if we enter tax code then in the output screen the respective G/L accounts with the amount credited should ap

  • Select list in JSP (Options from database)

    I am developing a web application on struts. I am having problem with my JSP. I have a form from where users input the keywords for search and when they click on a database query is performed and result is shown on the screen. Where i am stuck is tha

  • USING AN EXTERNAL HARDRIVE WITH OS LEOPARD AS A START UP DRIVE

    Can I start up using a firewire drive with Os X 5.8 installed, I like some of the programs that will not run in snow leopard