Getting LinkageError with class loader

I've written a class loader which extends java.net.URLClassLoader. My class is called EntryClassLoader. It only ovverides findClass() so that it will search a user-supplied path for a class. Beloww is the code:
public Class findClass(String className) throws ClassNotFoundException
try {
// First check to see if the user has prepended some
// directory path
if (className.indexOf(File.separatorChar) != -1) {
String path = className.substring(0,
className.lastIndexOf(File.separatorChar));
className = className.substring(className.lastIndexOf(File.separatorChar)
+ 1);
addURL(new File(path).toURL());
return super.findClass(className);
catch (MalformedURLException e) {
e.printStackTrace();
return null;
Here's a sample test program I've written:
public static void main(String args[]) throws Exception {
EntryClassLoader loader = new EntryClassLoader();
loader.findClass("TestPlayer");
loader.findClass("TestPlayer");
If I comment out the 2nd call to findClass(), the program runs fine, and I know that TestPlayer is successfully loaded. With the code as is however, I get the following error:
Exception in thread "main" java.lang.LinkageError: duplicate class definition: TestPlayer
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:509)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:246)
at java.net.URLClassLoader.access$100(URLClassLoader.java:54)
at java.net.URLClassLoader$1.run(URLClassLoader.java:193)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:186)
at nirex.EntryClassLoader.findClass(EntryClassLoader.java:33)
at TestLoader.main(TestLoader.java:8)
Could someone please explain why I might be getting this error. And I really don't understand why it works if I only call findClass() once. Thanks.
John

Check if findLoadedClass(className) is null and load only then. If findLoadedClass() returns a non-null value, the class has already been loaded.

Similar Messages

  • Plz help me out with class loader problem

    hai forum members,
    I have a code which loads class files from local disk.
    It works fine with some classes ,
    But i get this exception when i am selecting certain other class files
    I am using jdeveloper.
    Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: Filter (wrong name: project1/Filter)
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at com.jutframe.JavaUnitTester.selectClass_actionPerformed(JavaUnitTester.java:449)
         at com.jutframe.JavaUnitTester$7.actionPerformed(JavaUnitTester.java:338)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
         at java.awt.Component.processMouseEvent(Component.java:5488)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1766)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
                        JFileChooser jfilechooser=new JFileChooser();
                        Filterclass filter=new Filterclass();
                        //Set selection mode for file chooser
                        jfilechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        //set file filter
                        jfilechooser.setFileFilter(filter);
                        int returnVal = jfilechooser.showOpenDialog(this);
                        if(returnVal == JFileChooser.APPROVE_OPTION)
                            try
                                    String str = jfilechooser.getSelectedFile().getName();
                                    String parent=jfilechooser.getSelectedFile().getParent();
                                     // Create a File object on the root of the directory containing the class file
                                     File file = new File(parent);
                                     // Convert File to a URL
                                     URL url = file.toURL();         
                                     URL[] urls = new URL[]{url};
                                     // Create a new class loader with the directory
                                     ClassLoader cl = new URLClassLoader(urls);
                                     StringTokenizer st = new StringTokenizer(str,".");
                                     String s = st.nextToken ();
                                     Class c = cl.loadClass(s);  //ERROR IS SHOWN IN THIS PARTICULAR LINE
                                     Object instance=c.newInstance();
    --------------------------------------------please help me trace my mistake.
    thank you all.

    i think the problem that i have set a particular class path for my class files and my application loads files from that alone.
    So plz tell me if theres any way to access the class path of a particular file dynamically?
    regards

  • Performance issues with class loader on Windows server

    We are observing some performance issues in our application. We are Using weblogic 11g with Java6 on a windows 2003 server
    The thread dumps indicate many threads are waiting in queue for the native file methods:
    "[ACTIVE] ExecuteThread: '106' for queue: 'weblogic.kernel.Default (self-tuning)'" RUNNABLE
         java.io.WinNTFileSystem.getBooleanAttributes(Native Method)
         java.io.File.exists(Unknown Source)
         weblogic.utils.classloaders.ClasspathClassFinder.getFileSource(ClasspathClassFinder.java:398)
         weblogic.utils.classloaders.ClasspathClassFinder.getSourcesInternal(ClasspathClassFinder.java:347)
         weblogic.utils.classloaders.ClasspathClassFinder.getSource(ClasspathClassFinder.java:316)
         weblogic.application.io.ManifestFinder.getSource(ManifestFinder.java:75)
         weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:67)
         weblogic.application.utils.CompositeWebAppFinder.getSource(CompositeWebAppFinder.java:71)
         weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:67)
         weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:67)
         weblogic.utils.classloaders.CodeGenClassFinder.getSource(CodeGenClassFinder.java:33)
         weblogic.utils.classloaders.GenericClassLoader.findResource(GenericClassLoader.java:210)
         weblogic.utils.classloaders.GenericClassLoader.getResourceInternal(GenericClassLoader.java:160)
         weblogic.utils.classloaders.GenericClassLoader.getResource(GenericClassLoader.java:182)
         java.lang.ClassLoader.getResourceAsStream(Unknown Source)
         javax.xml.parsers.SecuritySupport$4.run(Unknown Source)
         java.security.AccessController.doPrivileged(Native Method)
         javax.xml.parsers.SecuritySupport.getResourceAsStream(Unknown Source)
         javax.xml.parsers.FactoryFinder.findJarServiceProvider(Unknown Source)
         javax.xml.parsers.FactoryFinder.find(Unknown Source)
         javax.xml.parsers.DocumentBuilderFactory.newInstance(Unknown Source)
         org.ajax4jsf.context.ResponseWriterContentHandler.<init>(ResponseWriterContentHandler.java:48)
         org.ajax4jsf.context.ViewResources$HeadResponseWriter.<init>(ViewResources.java:259)
         org.ajax4jsf.context.ViewResources.processHeadResources(ViewResources.java:445)
         org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:193)
         org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
         org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
    On googling this seems to be an issue with java file handling on windows servers and I couldn't find a solution yet. Any recommendation or pointer is appreciated

    Hi shubhu,
    I just analyzed your partial Thread Dump data, the problem is that the ajax4jsf framework ResponseWriterContentHandler triggers internally a new instance of the DocumentBuilderFactory; every time; triggering heavy IO contention because of Class loader / JAR file search operations.
    Too many of these IO operations under heavy load will create excessive contention and severe performance degradation; regardless of the OS you are running your JVM on.
    Please review the link below and see if this is related to your problem.. This is a known issue in JBOSS JIRA when using RichFaces / ajaxJSF.
    https://issues.jboss.org/browse/JBPAPP-6166
    Regards,
    P-H
    http://javaeesupportpatterns.blogspot.com/

  • Issue with class loading -  Java concurrent Program

    Hi ,
    We are facing a strange issue for one of our customer.
    Scenario :
    We have a Java Concurrent Program (A.java ) which refers another Java class (B.java) , we modified the file B.java for a fix and created a patch. after applying the patch and bouncing the apache ,we found that B.java is loaded the old version of the class file.
    We asked them to restart the concurrent manager and related services, still we see that old version of B.java is loaded. (confirmed by adding code throwing exception - throw new Exception from a specific line and found that its not getting thrown at run-time)
    Any clue on this?.
    Thanks
    Joseph George

    Deployed this file both tier - Database server tier and Application server tier.
    I have face same issue, Concurrent program not picking file application server tier. its picking file from database server tier.
    Thanks, Avaneesh

  • Master data is getting overwrite with delta load

    Hi,
    We have an issue like some some asset numbers are showing blank for wbs elemnts.So we did Full repair Request.So pblm is solved.But after daily delta loads it is getting over write and again asset numbers are blank..please let me know any suggestions?
    Regards,
    Baanu

    Ok, so your problem in the source-system itself. Since the update mode for master data is overwrite, when these records with blank fields are loaded they will replace the existing values and you will have blank values in your master data.
    Check whether the data is available in the tables in the Source-system. If you have made any enhancements to the DataSource using exits, check the code for the exit and try to find out if the data is being changed by the code.
    If there are no enhancements, check whether the master data is being properly maintained in the source system.

  • Getting arrays with Class.getDeclaredFields

    I would like someone to tell me how is it possible to change values in an array with the getDeclaredFields() method of class Class. I am able to get all fields of my class but i doesn't work with any kind of array..
    here is my Class :
    class Objet
    int index;
    int[] valeurs;
    I am able to change the value of index with this code:
    private void readObject( java.lang.Object o )
    java.lang.reflect.Field f[];
    java.lang.Class cl = o.getClass();
    f = cl.getDeclaredFields()
    try
    try
    f.setInt( o, 0 );
    catch ( java.lang.IllegalAccessException e)
    System.out.println("illegal access exception ");
    catch ( java.lang.IllegalArgumentException e )
    System.out.println("illegal argument exception");
    can someone please help me?
    thanks

    In order to make it work you should add f.setAccessible( true) before settung any value.
    You may also need to look at the serialization spec, especailly on storing and retrieving fields. http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/serial-arch.doc7.html#5253

  • When opening Final Cut Pro it keeps getting stuck with the loading circle and I have to force the quit so please help?

    I have a Macbook Air, still fairly new from July 4, 2014. Yesterday, I was editing some footage in Final Cut Pro, and the colored spinning circle kept popping up. I continuously forced the quit, as I couldn't do anything, and then I restarted and looked for updates (though there was none). I then deleted the app and reinstalled it, but it's still giving me the same problem. This morning, I created a new user account, and Final Cut Pro works on that account, but it took some time to find the exported video (I actually had to turn it off and turn it back on to find the video). Later today, I went onto the main account, where Final Cut Pro isn't working, and it's still giving me trouble, and then the Picture Preview program got stuck, as well, twice, where I had to also force it to quit. What's happening? How do I fix this problem?

    The info given below might help but if it doesn't, I'm sure other people will give you useful suggestions.
    Corrupt preferences can create a vast range of different symptoms, so whenever FCP X stops working properly in any way, trashing the preferences should be one of the first things you do using this free app.
    http://www.digitalrebellion.com/prefman/
    Shut down FCP X, open PreferenceManager and in the window that appears:-
    1. Ensure that  FCP X  is selected.
    2. Click Trash
    The job is done instantly and you can re-open FCP X.

  • WebLogic class loading conflict causing ClassCastException

    Hi everyone,
    I am using Oracle XML Parser v2 for my JCA adapter and I am getting the following exception when method from my adapter is invoked.
    java.lang.ClassCastException: weblogic.xml.jaxp.RegistryDocumentBuilderFactory cannot be cast to oracle.xml.jaxp.JXDocumentBuilderFactory
    I have already placed Oracle XML Parser v2 library (xmlparserv2.jar) inside $DOMAIN_DIR/lib. Below is the line that throws above exception.
    JXDocumentBuilderFactory factory =(JXDocumentBuilderFactory)JXDocumentBuilderFactory.newInstance();
    So it seems like WebLogic is using different JXDocumentBuilderFactory and there seems to be problem with class loading. How can I resolve this issue? Thanks in advance.
    Regards,
    K.H
    Edited by: K Hein on Dec 16, 2010 12:38 AM

    HI,
    You can use Class Loader Filtering feature of WebLogic to isolate the Classloaders....as described in the following link: http://middlewaremagic.com/weblogic/?page_id=192
    Thanks
    Jay SenSharma
    http://middlewaremagic.com/weblogic (Middleware Magic Is Here)

  • Integrated WL/Jdeveloper class loading issue

    Hello,
    I am trying to run a deployed project , getting into this class loading issue. Any idea?
    javax.security.auth.login.LoginException: java.lang.LinkageError: loader constraint violation: when resolving interface method "com.scat.util.identity.UserFactory.lookup(Ljava/lang/String;)Lcom/scat/domain/identity/User;" the class loader (instance of weblogic/utils/classloaders/ChangeAwareClassLoader) of the current class, com/scat/auth/authentication/login/UserLoginModule, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for resolved class, com/scatl/util/identity/UserFactory, have different Class objects for the type com/scat/domain/identity/User used in the signature
    Thanks
    Ram

    How many times are you loading the com/scat/domain/identity/User type?
    Is this in the system classloader and the application? and are you using class loading filtering in the application, for example,
    in weblogic.xml - prefer-web-inf-classes?

  • How can I get a dynamic list of Classes Loaded

    I assume this may need to use some sort of reflection. Does
    anyone have code or ideas where I can:
    a) I can get a list of all Classes loaded and their
    properties. This would probably be all instances of Class
    b) A list of all
    global instance variables. (This may not even be possible. I
    know it can be done in other languages)
    I assume this may need to use some sort of reflection.
    Thank you

    Adobe Newsbot hopes that the following resources helps you.
    NewsBot is experimental and any feedback (reply to this post) on
    its utility will be appreciated:
    mx.controls.List (Flex 3):
    If the data is incorrect, you can call the preventDefault()
    method to stop Flex from passing the new data back to the list
    control and from closing the
    Link:
    http://livedocs.adobe.com/flex/3/langref/mx/controls/List.html
    Displaying icons in a Flex List control at Flex Examples:
    http://blog.flexexamples.com/2007/08/17/displaying-icons-in-a-flex-list-control/
    --> <mx:Application xmlns:mx=&quot;
    http://www.adobe.com/2006/mxml&quot;
    Link:
    http://blog.flexexamples.com/2007/08/17/displaying-icons-in-a-flex-list-control/
    Populate the list -- Flex 2.01:
    You populate a list-based form control with the
    <mx:dataProvider> child tag. The <mx:dataProvider> tag
    lets you specify list items in several ways.
    Link:
    http://livedocs.adobe.com/flex/201/html/tutorial_controls_019_4.html
    Smooth Scroll for Horizontal List - Flex India Community |
    Google:
    I have created image gallery with Horizontal List[Flex 2.0].
    Just as below ref site. My Problem is i need a smooth scroll for
    Horizontal List. where images
    Link:
    http://groups.google.com/group/flex_india/browse_thread/thread/a12441143b98d32c?hide_quote s=no
    Creating a List control -- Flex 2.01:
    The following example code adds a handler for a change event
    to the List control. Flex broadcasts a mx.ListEvent.CHANGE event
    when the value of the control
    Link:
    http://livedocs.adobe.com/flex/201/html/dpcontrols_062_03.html
    Disclaimer: This response is generated automatically by the
    Adobe NewsBot based on Adobe
    Community
    Engine.

  • Dynamic class loading with Webstart

    Hello !
    //within the jar-file at the webstart-directory
    public interface MyFrame{
    public void createFrame();
    //within the jar-file dynamically downloaded
    public class MyExtFrame extends JFrame implements MyFrame{
    String className = "MyExtFrame";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    JarClassLoader jarLoader = new JarClassLoader (cl, jarFile));
    /* Load the class from the jar file and resolve it. */
    Class c = jarLoader.loadClass (className, true);
    /* Create an instance of the class.
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof MyFrame){
    // Yep, lets call a method we know about. */
    MyFrame client=(MyFrame) o;
    //call a class-method (here creates the whole gui-object at once)
    client.createFrame();
    This is the code i'm using and i've encountered following problem, if i put this code into an application without webstart, anything works fine, but with webstart i'll get a: java.lang.NoClassDefFoundError
    Then i've put the MyFrame-classes into the downloaded jar-file, but this won't work either, i'll get a ClassCastException.
    What do i have to do, to become it working ?
    Thanks for any conclusions and help.
    Michael

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Problem with dynamic class loading

    Hi,
    We have a class file in an external jar(outside ear) and access it in an ear using classloader.loadClass method. But if the class file is changed in jar, it gets hotdeployed in jboss but code which calls this class still refers to the old code.
    Class getClassByName(String className) throws ClassNotFoundException {
    Class theClass = null;
    try {
    theClass = Thread.currentThread().getContextClassLoader().loadClass(className);
    } catch (ClassNotFoundException e) {
    theClass = getClass().getClassLoader().loadClass(className);
    return theClass;
    When I looked into api I came to know that loadClass actually loads the class if it is not already exists. Can any one help me in writing thecustom class loader which loads the class everytime instead of checking previous instance before loading......
    Thanks,
    Kruthika

    You probably have to get rid of the class loader that loads the original version and start with a new class loader.

  • I get the "unable to load data class information" why I try and sync

    I get the "unable to load data class information" when I try and sync with my iPad.  Tried uninstall and reset sync history, still doesn't work.  Help.

    Hey Mike Urwin
    Start with the article below for troubleshooting syncing issues with Sync Services.
    Advanced troubleshooting for Sync Services on Windows with Microsoft Outlook 2003, Outlook 2007, or Outlook 2010
    http://support.apple.com/kb/TS2776
    Regards,
    -Norm G.

  • Getting all classes loaded by ClassLoader?

    How do you get an array of type (Class []) that represents all the classes loaded by a ClassLoader?
    Thanks
    neofreezer

    but if you do, that means that u can't load classes whose packages start with 'java.'!

  • Hi, I've recently bought an iPad2 and can't get connected with AppStore or iTunes, when I tap on these icons a grey page pops up saying is loading but never opens the page, no failure message is displayed, it just keep saying is loading. Apparently it is

    Hi, I’ve recently bought an iPad2 and can’t get connected with AppStore or iTunes, when I tap on these icons a grey page pops up saying is loading but never opens the page, no failure message is displayed, it just keep saying is loading.
    Apparently it is not an issue with wifi since Safari, You Tube and Maps work well, I’ve tried some of the tips, e.g. log off/on my Id, change password but no one worked.
    Your help will be highly appreciated.
    Thank you.
    Luis.

    Try a reset. Hold the Sleep and Home button down for about 10 seconds until you see the Apple logo. Ignore the red slider.

Maybe you are looking for

  • MacBook Pro shuts down when opened

    This has just randomly started happening this evening. Whn I close the lid for my MBP, everything happens as normal, but then when I open it, sometimes the login screen will appear for a brief moment or two then close as if when the lid is open, the

  • The cap lock key doesnt work sometimes, why? 13 pro(2013, late)

    The cap lock key doesnt work sometimes, why? 13 pro(2013, late)

  • Finder window shifts content off screen to the left.

    This is posted in the Finder discussion also. I post it here also in the chance this is a Retina display issue. I never experienced this problem with Lion on my old MacBook Pro, just on my new Retina display. On several occasions the window in my Fin

  • All I want to do is CRUD an Object to a Database

    I don't need security or transactions or XML marshalling or caching. I just want to CRUD! First I started with simple JDBC. Tables of tables of tables. Very tedious. Then I tried JAXB->XML->Oracle XML DB. A little bleeding edge. Vendor specific solut

  • 1. Installed maps on Nokia N900 not showing - 2. k...

    Although I have installed local maps dae through nokia maploader to Nokia N900, when I start the Map app on the phone the data is missind. Instead it downloades it from internet. I must clarify that if I reset the phone by reupdating the software the