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...

Similar Messages

  • 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;

  • 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 a class dynamically and then a call a method?

    Hi
    I want to call a method from a class,which class is loaded dynamically.
    Consider a classA and ClassB..
    ClassB contains a method showvalue() which returns a String value.
    I want to load a ClassB dynamically in ClassA,and call the method showvalue() and print the returned value of that method (showvalue).
    How to do this?
    Thanks

    Since you found your way to Reflections and Reference Objects, I can only assume you know that reflection is the answer. Since the reflection tutorial on this site, and indeed, the many others on the web, can explain this a whole lot better and more consisely than can be done in a forum, I'll point you in that direction instead. As a starting point, and to show I'm not just fobbing you off, you're interested in the classes java.lang.Class, java.lang.reflect.Method, and the method Class.getMethod(String, Class[])

  • Loading updated classes dynamically

    Hi,
    I have some classes in the classpath which I am modifying and using them in the
    weblogic. I have to restart the weblogic if those updated classes are to be loaded.
    Is there any way by which weblogic can automatically take those classes whenever
    they are accessed .
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    TIA
    Ashwani Kalra
    http://www.geocities.com/ashwani_kalra/
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    I believe the same is true for 5.1. Just include all supporting
    classes to your ejb-jar. What's the problem?
    Regards,
    Slava Imeshev
    "Kiran Nalamk" <[email protected]> wrote in message
    news:3c4e2e0d$[email protected]..
    >
    Hai,
    I am also facing same problem with Wl5.1 can you help me on Wl5.1also what
    we need to do. Thanx in advance.
    Kiran Nallam
    "Slava Imeshev" <[email protected]> wrote:
    Hi Ashwani,
    All classes that are in the system class path are loaded by the
    system classloader and, as the result, can not be reloaded by
    weblogic. You need to compose your deployment properly.
    Remove classes you want to be reloaded from the classpath
    and include them into your deployments instead.
    Regards,
    Slava Imeshev
    "Ashwani" <[email protected]> wrote in message
    news:3c47d920$[email protected]..
    Hi,
    I have some classes in the classpath which I am modifying and usingthem
    in the
    weblogic. I have to restart the weblogic if those updated classes areto
    be loaded.
    Is there any way by which weblogic can automatically take those classeswhenever
    they are accessed .
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    TIA
    Ashwani Kalra
    http://www.geocities.com/ashwani_kalra/
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • Loading Jar classes dynamically - 10 Duke points

    How can I load a jar class dynamically if it relies on say other interface? Example is, if I have three classes read from the jar file, Test.class, Test1.class and Testable.class
    and "class Test implements Testable..."
    If I load the Test.class, how do I tell my own class loader that Testable class is along the way, instead of getting a java.lang.NoClassDefFoundError: Testable
    Need example source that works for this type of problem.
    Cheers
    Abraham Khalil

    protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {     
    name = name.replace('/', '.').replace('\\', '.');
    try { 
    // check if system class
    return findSystemClass(name);
    catch (ClassNotFoundException e) {}
    catch (NoClassDefFoundError e) {}
    // check if class already loaded
    Class cl = null;
    JarClassEntry jarEntry = (JarClassEntry) classes.get(name);
    if (jarEntry != null) { // new class not loaded
    // load class bytes--details depend on class loader
    byte[] classBytes = loadClassBytes(name);
    if (classBytes == null) {
    throw new ClassNotFoundException(name);
    String className = name;
    if (className.endsWith(".class")) {
    className = className.substring(0, className.indexOf(".class"));

  • 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 in the current/system class loader

    I need to dynamically load a new jdbc driver jar to the current/system class loader... Please note that creating a new classloader will not help since the DriverManager refers to the systemclassloader itself.
    Restarting the application by appending the jar to its classpath will solve the problem but I want to avoid doing this.

    Did you then create a ClassLoader to load the JDBC
    driver and then install it into the system as
    directed by the JDBC specification (ie
    Class.forName(someClassName))?
    And then try to use it from a class loaded fromsome
    other ClassLoader (i.e. the system class loader)?
    If you did not try this please explain why not.O.K. I just looked at the source to
    java.sql.DriverManager. I did not know what I was
    talking about, as what I suggested above will not
    work.
    This is my new Idea:
    Create a URLClassLoader to load the JDBC driver also
    in this ClassLoader you need to place a helper class
    that does the following:
    public class Helper {
    public Driver getJDBCDriver(String driverClassName,
    String url) {
    try {
    Class.forName(driverClassName);
    Driver d = DriverManager.getDriver(url);
    return d;
    catch(Exception ex) {
    ex.printStackTrace();
    return null;
    }Now create an instance of the Helper class in the new
    ClassLoader, and call its getJDBCDriver method to get
    an instance of the driver (you will probably have to
    create an interface in the root class loader that the
    Helper implements so that you can easily call it).
    Now from the root classloader you can make calls
    directly to the returned Driver and bypass the
    DriverManager and its restrictions on cross
    ClassLoader access.
    The only catch here is that you would have to call to
    the returned Driver directly and not use the Driver
    Manager.This sounds like will work but I did not want to load DriverManager in a new classloader.. I did a hack
    I unzip the jar dynamically in a previously known location (which I included in my classpath when launching the app). The classLoader finds the class now though it did not exist when the app was launched !
    A hack of-course but works eh ..

  • 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).

  • Loading JDBC driver dynamicly (without CLASSPATH)

    Problem:
    Need loading driver for database MySQL without
    using enviroment variable CLASSPATH.
    I try this using URLClassLoader
    URL []url = new URL[1];
    url[0] = new URL("file:\\d:\\Sergei\\Work\\MySlateDB\\MySqlDriver\\mm.mysql-2.0.6.jar");
    URLClassLoader loader = new URLClassLoader(url);
    DriverManager.registerDriver((Driver)Class.forName("org.gjt.mm.mysql.Driver",true,loader).newInstance());//.newInstance();
    Enumeration e=DriverManager.getDrivers();
    Driver loading, but DriverManager do not register it.
    Enumeration e is empty....
    Connection cn = DriverManager.getConnection("jdbc:mysql:\\172.16.9.200\\astra?user=SERGEY&password=QWE");
    And accordingly create exception "no Suitable driver"
    Why DriverManager do not register driver ?
    if add jar-archive in CLASSPATH then all working.
    How solve this problem ?
    Best regards, Rinver.

    You going to have to write your own version of DriverManager to do this. java.sql.DriverManager only uses the system classloader to load JDBC drivers.
    You can get an example from here:
    http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/squirrel-sql/squirrel-sql/fw/src/net/sourceforge/squirrel_sql/fw/sql/
    The files you are interested in are SQLDriverManager.java and SQLDriverClassLoader.java.
    Col

  • 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

  • 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

  • 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 , which isn't in the classpath environment variable.

    Hi, you folks.
    I have one problem. I want to load a class, which isn't in the classpath
    environment variable and I don't want to put into classpath. which method
    JVM can use to load it?
    Waitting for your sage advice.
    Regareds
    Hunter.Xiao

    You will have to write your own ClassLoader, or use something like URLClassLoader (I've never used this myself, but I've seen it mentioned elsewhere in this forum). Look here.

  • Dynamically loading a class that is part of a larger loaded package

    I am dynamically loading a class that is part of a large package, much of which is loaded at startup. The code directly references protected variables in the parts of the package that is loaded by the default class loader. Attempting to access these protected variables gives an access error when the class is dynamically loaded that doesnt occur when the class is loaded at startup.
    Is there a way to make this work?

    To answer my own question -- no
    A reference from http://access1.sun.com/techarticles/DR-article.html says:
    The use of Dynamic Class Reloading can introduce problems when classes that are being dynamically reloaded make calls to non-public methods of helper classes that are in the same package. Such calls are likely to cause a java.lang.IllegalAccesserror to be thrown. This is because a class that is dynamically reloaded is loaded by a different classloader than the one used to load the helper classes. Classes that appear to be in the same package are effectively in different packages when loaded by different classloaders. If class com.myapp.MyServlet is loaded by one classloader and an instance of it tries to call a non-public method of an instance of class com.myapp.Helper loaded by a different classloader, the call will fail because the two classes are in different packages.
    So not being able to access non-private variables in this scenario is the way it works.

Maybe you are looking for