Loading a class from specified classpath

Hello,
I would like to create an instance of a class in a specific directory.
So, I am doing this way :
System.setProperty("java.class.path", classPath.getAbsolutePath());
Class object = Class.forName(name);
Object instance = object.newInstance();It works perfectly when running in my IDE (Eclipse).
But when I am running my application through a JAR, I encountered the following error :
ClassNotfoundException
I don't understand why an exception is thrown whereas I defined correctly my classpath.
Could you help me ?

When running from an executable jar the normal class path is ignore in favour of thejar and any Class-Path specified in the jar's manifest.
What you want is a URLClassLoader. Bascially:
URLClassLoader cl = new URLClassLoader(new URL[]{classPath.toURL()});
Class clazz = cl.loadClass(fullName);(Catch assorted exceptions)
There should not be a class of the given name in the jar, or libraries it references (if there is, that will be loaded in preference).

Similar Messages

  • Problem loading modified classes from CLASSPATH using system class loader

    Hi,
    I am facing problem to load the modified classes from CLASSPATH.
    I have set my CLASSPATH to a directory whose classes will be modified frequently. After the server(web/app) is started, the system class loader, using which am trying to load the classes from the directory where the CLASSPATH is set, am not able to load the modified files without the server restart.
    Do I need to have a custom class loader to fix this.
    Please help me.
    Thanks,
    Sureddy

    Do I need to have a custom class loader to fix this.Yes.

  • Can't load any classes from infobus.jar (WL 6.0 SP1)

    Hi,
    I am deploying an .ear file, which has one .war file in it. The war file, has
    infobus.jar, inside it under \WEB-INF\lib. Whenever in my servlet code I try to
    load a class from infobus.jar, I get the following exception :
    About to load class javax.infobus.InfoBusDataConsumer<<<<<<<<<<java.lang.ClassNotFoundException: InfoBusDataConsumer
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:178)
    at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:45)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:313)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:120)
    at XDILoginForm.init(XDILoginForm.java:99)
    at weblogic.servlet.internal.ServletStubImpl.createServlet(ServletStubImpl.java:638)
    at weblogic.servlet.internal.ServletStubImpl.createInstances(ServletStubImpl.java:581)
    at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:526)
    at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1078)
    at weblogic.servlet.internal.WebAppServletContext.preloadServlets(WebAppServletContext.java:1022)
    at weblogic.servlet.internal.HttpServer.loadWARContext(HttpServer.java:499)
    at weblogic.servlet.internal.HttpServer.loadWebApp(HttpServer.java:421)
    at weblogic.j2ee.WebAppComponent.deploy(WebAppComponent.java:74)
    at weblogic.j2ee.Application.deploy(Application.java:175)
    at weblogic.j2ee.J2EEService.deployApplication(J2EEService.java:173)
    at weblogic.management.mbeans.custom.Application.setLocalDeployed(Application.java:217)
    at weblogic.management.mbeans.custom.Application.setDeployed(Application.java:187)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.management.internal.DynamicMBeanImpl.invokeSetter(DynamicMBeanImpl.java:1136)
    at weblogic.management.internal.DynamicMBeanImpl.setAttribute(DynamicMBeanImpl.java:773)
    at weblogic.management.internal.DynamicMBeanImpl.setAttribute(DynamicMBeanImpl.java:750)
    at weblogic.management.internal.ConfigurationMBeanImpl.setAttribute(ConfigurationMBeanImpl.java:256)
    at com.sun.management.jmx.MBeanServerImpl.setAttribute(MBeanServerImpl.java:1356)
    at com.sun.management.jmx.MBeanServerImpl.setAttribute(MBeanServerImpl.java:1331)
    at weblogic.management.internal.ConfigurationMBeanImpl.updateConfigMBeans(ConfigurationMBeanImpl.java:318)
    at weblogic.management.internal.ConfigurationMBeanImpl.setAttribute(ConfigurationMBeanImpl.java:259)
    at com.sun.management.jmx.MBeanServerImpl.setAttribute(MBeanServerImpl.java:1356)
    at com.sun.management.jmx.MBeanServerImpl.setAttribute(MBeanServerImpl.java:1331)
    at weblogic.management.internal.MBeanProxy.setAttribute(MBeanProxy.java:291)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:173)
    at $Proxy7.setDeployed(Unknown Source)
    at weblogic.management.console.pages._panels._mbean._application._jspService(_application.java:303)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:213)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:1265)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:1622)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    But if I put the infobus.jar on system classpath , everything works out fine.
    Can somebody tell me, what is going on

    Gseel is right: you try to instantiate an EJB with the BDK.
    Enterprise Java Beans are totally different from graphical/GUI beans. EJBs are thought for dealing with business logic like accessing a database, ldap directory and so on. They run on a application server (simply speaking - a java enabled webserver) and do some processing to handle user requests. Enterprise Java Beans usually don't interact directly with the user, they only do the work in the background and forward their results, which are then rendered for the user. Typically they are employed for handling web requests (a user with a browser), but they can also be used for awt/swing applications. Though - let me repeat - they don't appear visually on the screen.
    The only similarities between those two bean types are the following: they have getter/setter methods for their properties, they implement Serializeable (or a sub-interface like Externalizable, Remote) and they have a default no-argument constructor.
    If you want to run your been you need an application server (your bean is pre-packaged for the Bea Weblogic app-server). If you want to do something graphical, you'll need to search for GUI beans.
    dani3l

  • Problem in loading a class from server

    hello,
    Please help me ,i m using this code to load a class from server and this code load this successfully but i don't how to make object of class that is just loaded.
    i want to load the class and use its method in my program please help me i m in very critical position.
    pelase help me give me hint
    import java.sql.*;
    import java.net.*;
    import java.io.*;
    public class MyLoader
    public static void main (String argv[]) throws Exception
    URLClassLoader loader = new URLClassLoader(new URL[] { new URL("url") });
    // Load class from class loader. argv[0] is the name of the class to be loaded
    String str = "FinalMyConnection";
         Class c = loader.loadClass (str);
    System.out.println(c.getClass().getName());
    // Create an instance of the class just loaded
    Object o = c.newInstance();
         System.out.println(o.getClass());
         FinalMyConnection mycon = new FinalMyConnection();
         String query1 = " select * from game_master order by game_id;";
         mycon.connect();
              ResultSet rs1=mycon.executequery(query1);
              while (rs1.next())
              String s1=rs1.getString(1);
                   String s2=rs1.getString(2);
                   System.out.println("game_id"+s1);
                   System.out.println("game_name"+s2);
    }

    also load all required parser and sax classes into oracle,i.e.,
    you can load the '.jar' file containg all the parser and sax classes and then load you ContentHandler class.

  • Loading a class not on classpath

    how can we load a class not on classpath?

    uddinr0121 wrote:
    try this
    private void addArchive(File jarFile) throws IOException {
    URL u = jarFile.toURI().toURL();
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<?> sysclass = URLClassLoader.class;
    try {
    Method method = sysclass.getDeclaredMethod("addURL", parameters);
    method.setAccessible(true);
    method.invoke(sysloader, new Object[]{u});
    } catch (Throwable t) {
    t.printStackTrace();
    }this will add the jar file to the classpath after which you should be able to invoke using Class.forName()
    hope this helpsThat's a horrible solution, when you can just create a new URLClassLoader and use that to load the class.
    Adding it to the system classpath with reflection trickery is not really a clean solution to that.

  • 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

  • Loading a class dynamically to classpath

    I have a class object for my .class file. It thougth it would be loaded to the classpath dynamcially by resolveClass(Class c), but still i am not able to add my class to the VM's classpath.
    Can anybody help,
    Thanks in advance
    Amir

    how do you get that Class object?
    If you use Class.forName(java.lang.String), the class loads itself, if found in classpath.
    If the class is dynamicaly generated, and you have the the file, or the bytes that form the class, you may invoke
    ClassLoader.defineClass(String name, byte[] b, int off, int len)
    I have no idea if my answer is anywhere near what you expect...

  • Is there a restriction on loading "javax" classes from WEB-INF/lib?

    I'm having trouble with a webapp in WL 10MP1 that is having trouble loading classes from the "jsr311-api-1.0.jar" in my WEB-INF/lib. Even though I have no trouble with it in Eclipse (no compile errors), classes from that jar fail with "NoClassDefFound" exceptions. I have a feeling it might be the fact that the packages in that jar start with "javax". Assuming that's the case, is there anything I can do to fix this?
    What's even stranger is that the errors I get are when I try to load them directly from the Spring context. However, if I remove the test references to those classes, there's other code that loads those classes later in the application startup (after the Spring context finishes loading), and they load perfectly fine (I turned on verbose class loading to verify this).

    Note that I've tried two other strategies that both result in the same failed state.
    I tried putting the "jsr311-api-1.0.jar" in $JDK_HOME/jre/lib/ext, but that causes a failure to find Spring classes. I then copied the "spring.jar" into $DOMAIN_HOME/lib, and then it fails to find CXF classes. After doing the same with "cxf-2.2.3.jar", it then fails to find "javax.servlet.ServletContextListener", which clearly tells me there's no benefit to this approach.
    Similarly, I tried copying the jars into $DOMAIN_HOME/lib, and that fails to find "org.apache.commons.logging.LogFactory". I could continue down this path, but it doesn't seem likely to succeed. Eventually, I'll get to a point where it just can't find the classes specific to my application, which I certainly can't copy into $DOMAIN_HOME/lib.
    The first basic problem is that I can't put anything into a higher-level classloader that will eventually reference classes in a lower-level classloader, because references can only go up the chain, and the second problem is that WebLogic appears to ignore classes in WEB-INF/lib in the "javax.*" packages. I think there might be an exception for "javax.xml.*", but not for other subpackages. I tried adding a "prefer-application-packages" clause to my weblogic-application.xml file, but that had no effect.

  • How to load a class from its name.

    Hi,
    In my program, I want users can write their own classes, these classes need to implement an interface and name of class will be stored in database. I use Class.forName() to load these classes but I cannot type-cast to interface. Please help me.
    Here is the code in my program:
    public interface A {
    public void doSomething();
    public class test {
    public static void main(String[] args) {
    A clazz = (A)Class.forName("MyClass"); // error here
    A.doSomething();
    }

    Hai,
    Refine your test class as follows:
    public class test
    public static void main(String arg[])
    try
    Class clazz = Class.forName("MyClass");
    Object obj = clazz.newInstance();
    ((MyClass)obj).doSomething();
    catch(Exception ex)
    System.out.println(ex);
    Regards
    Raja.

  • How to load a class from a jar not in the classpath

    I have a gazillion jars of class files that I want to access dynamically in an application. I don't want to list every jar. The jars also contain images. With images you can explicitly point to the jar with and load the image with createImage....
    "jar:file:/C:/myjarlocation/myjar.jar!/pathtoimage/image.gif"
    Is there a similar string you can use when creating classes on the fly in a classloader with getClass().forName("classname") ??

    Hm, if you are not in an EJB container or some other environment that won't let you create a classloader, you might create a new URLClassLoader with a path pointing to those JARs. You will probably want to use your normal application class loader as the parent loader, so any referenced common class definitions are found during the load.
    Note that - in order to make use of the classes - you will normally need to know that they implement some interface (or inherit from a common base class) to which you can cast their instances. These Interfaces/base classes will have to be packaged for normal loading by your application class loader; else the cast will trigger an error during compile time. After this, loading them dynamically during runtime is no longer an option since they are referenced directly in the sourcecode.
    Alternatively you might do away with interfaces/base classes and call methods of dynamically loaded classes also dynamically: via reflection. But I guess this is too cumbersome for what you might have in mind. Also it has more invocation overhead, less type safety and handling all these exceptions wrapped in InvocationTargetExceptions can quickly become a nightmare too...

  • Not able to load jspx file from the classpath in Integrated OC4J

    Hi,
    I am using integrated OC4J from my jdeveloper to deploy my application as an ear file. It contains one jar file (with ejb deployment desscriptors) and a war file (including Model and Viewcontroller project contents).
    The war file contails a jspx file (say Test.jspx) which contails a link to another jspx file (say Remote.jspx) which resides in its WEB-INF/lib directory.
    When I load Test.jspx and click on the link, it fails to look for the Remote.jspx. It displays a message "OracleJSP error: java.io.FileNotFoundException:" on the web browser.
    From the message written to log file, found that it is actually trying to search for Remote.jspx file in the current context.
    Also tried including the classpath to the jar file containing the Remote.jspx file in orion-web.xml of the web application. using the following:
    <classpath path="file:/xxx/yyy.jar" />
    The issue is still there even after this.
    Can anyone suggest me how to achieve this?
    Thanks,
    Aparna

    this.getCodeBase(), would get RSPL / RLog or whatever you have in your codebase (html parameter of
    the OBJECT/APPLET(:hope not) tag.
    URL u = new URL(this.getCodeBase(), "../something.jpg");
    would get RSPL/something.jpg
    URL u = new URL(this.getCodeBase(), "../VIRA/JPG/00/1.jpg");
    would get RSPL / VIRA / JPG / 00 / 1.jpg
    If you are not sure what your codebase is your can print it out:
    System.out.println(this.getCodeBase().toString());

  • Unable to load Java classes from byte arrays.

    I have an application started through JWS. It works fine except for one problem. The application allows the user to load an external class, typically received over a socket. These are not (and cannot) be signed. My application complains about not being able to load these when starting through JWS. When starting the application locally (i.e., run the jar file using 'java -jar APP.jar') it works fine.
    I guess I have to grant som additional permissions in my policy-file. But since these classes are user-defined, there is no way for me to define a static codebase. `
    Any ideas?

    Java Web Start installs a SecurityManager, and after that is responsible for assigning permission collections to any code loaded by the JNLPCLassLoader.
    If you have all-permissions for your jnlp loaded code, then use another ClassLoader to load some other code, That other class loader will assign the permissions to that code. If that ClassLoader dosn't extend SecureClassLoader, the code will get only the default permissions.
    You can fix this by
    1.) Use a ClassLoader that extends SecureClassLoader, and override getPermissions(), or
    2.) just call System.setSecurityManager(null), from the trusted code loaded by the JNLPCLassLoader.
    /Dietz

  • Load java class from another directory

    Hi. I am new to Java. I am trying to load a java object from a subdirectory. Is that possible? Thanks in advance!

    Thanks for the quick reply!
    I tried this:
    set CLASSPATH =
    Data;Application;Entertainment;MiniGames;
    but it doesn't seem to work...
    The actual subdirectory is
    \Data\Application\Entertainment\MiniGames
    I am new to Java, so please bear with me with my
    stupidity... please advice again.
    Thanks in advanceClasspath needs to contain the actual directory paths, not a relative path. So it should be something like .;c:\Data\Application\Entertainment\MiniGames

  • Load a class from strea

    Hi i have a strange problem:i save a class object in a database blob then i want to read the object and set them in to the class path.Is possible?

    i save a class object in a database blob then i want to read the object Do you save a Class or an instance of that Class?
    set them in to the class path.Is possible?If you want to save a Class and load it, you need a custom ClassLoader which can read the blob and call defineClass with the bytes.
    If you want to save an Object and load it, you need to read the bytes and then use an ObjectInputStream to read the object. The Class must be on the system classpath or you need to subclass ObjectInputStream and (I think) override resolveClass.

  • Loading all classes on classpath

    Hello!
    I'm trying to create some kind of "Package browser" which I can use for selecting a class that exists on the classpath.
    I've come up with a solution that reads the classpath property and then looks up the classes by searching each directory and jar-file for class files. These are presented in a JTree. This solution has a drawback though. When using Visual Age for Java, my app won't find any class files on the classpath as these are not added to the local file system. It seems Visual Age has it's own ClassLoader which loads classes from it's own repository rather than from the file system.
    Now I wonder, is there another way to load all classes from the classpath?
    Regards,
    Pelle Poluha

    Visual Age uses the "system" classpath alright. When I add another directory to the classpath using VA, my "package browser" recognizes this but shows an empty directory. And it is empty on my local file system. What I can do is to export all the classes I need to a directory or jar-file and then add this to the classpath. Then my app recognizes the classes. But this is too cumbersome.
    What I need, I guess, is a way of communicating with the current classloader and get it to return all classes/packages in a given package. Anybody knows if that's possible?
    Regards,
    Pelle Poluha

Maybe you are looking for

  • Zen V Plus: Software barrier against installing US firmware on european devic

    Well well... After the "display darkening devil" caught me, I just decided to buy a new player because I need this thing frequently when I'm on the road. Now I've got a Zen V Plus but there is a DIFFERENCE. "Sure, the FM Radio!" True, but there is an

  • What is the effective ADC resolution of the Usb6361 board

    I have been using a USB-6361 board with 16-bit ADC. I went to simulate a lower bit count ADC implementation and I noticed that the data sampled from the 6361 does not appear to have 16-bit resolution. Here's an example of some of the waveform samples

  • Editing in Standard or Pro

    Hi! Trying to nail down the version I need to do the following: Reduce file size Extract (break up) pages Can these be done with XI Standard or do I need Pro? Any guidance will help. Thank you!!

  • Will not show pdf, pop up blocke is off,

    when it comes up it's just black, I'm trying to view statments on line

  • Inner join driving table

    Hi, we have 2 dimension tables and 1 fact table. So our physical query looks like the below: Select a, b, c.... from BC_CTR T89740, M_CTR T49296, BC_M_FCT T59920 where T49296.CTR = T59920.M_CTR and T89740.CTR = T59920.BC_CTR The problem we face is th