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();

Similar Messages

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

  • 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 i load java class through javascript

    Hi,
    i want to load java class file at client side through the java script. Class file wich already at client side(client machine)
    tell me is it possible....
    thanks
    plzz mail
    [email protected]

    From your post it is not very clear what you want to do.
    1. Even if it was possible to load client classes using javascript, how on earth are you going to execute them ??? JavaScript and java are entirely different cups of tea.
    2. If it was an applet, then probably you can access some classes from the client machine. Definely the default packages. However, I don't know whether you can access other classes. That might lead to a security issue. Please check with a java securities expart.
    3. Loading a class from the client machine is DEFINITELY A BAD PROGRAMMING PRACTICE Use the codebase property on your applet tag to load the classes from the server.

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

  • How to load 50 class ?

    hi, suppose i need to load 50 class.(no other way but to load ) what is the best way ?

    hi, suppose i need to load 50 class.(no other way but to load ) what is the best way ?Use a loop around the static class.forName(String clazz) method?
    kind regards,
    Jos

  • 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[])

  • How to "Load" Applet class to current Applet?

    I have to write a simple Applet to detect the JVM version of the browser, and the flow is:
    1.Detector.class (Applet) load in a html page, its class version is 1.5
    2.It checks whether the JVM version of the browser is 1.5 / 1.6.
    3.If it is 1.5, a new browser window popup and links to jre download page.
    4.If it is 1.6, it loads a Main.class (Applet), which class version is 1.6
    My question is, if the codes inside the Detector.class detects the JVM version is 1.6, HOW can I LOAD the Main.class (Applet) to the current scene?
    Thanks for any suggestion and help.

    roamer wrote:
    ..My question is, if the codes inside the Detector.class detects the JVM version is 1.6, HOW can I LOAD the Main.class (Applet) to the current scene?
    Thanks for any suggestion and help.I suggest you change the flow.
    1. Go to the applet page with both the Main.class *&* the version check applet.
    2. If <1.6 is detected, have the version check applet redirect to the the 'download Java' page.
    Alternately:
    1. Go to the version check page.
    2. If 1.6+ is detected, redirect to the Main.class page, else redirect to 'download Java' page.
    I developed the [Version Check|http://pscode.org/jre.html] applet that can handle either of those alternatives.
    Another approach is to use the deployJava.js that checks Java versions before launching the applet.
    I also offer Wrapplet to do both the version checking and load 'child' applets. But note:
    1) With the other better alternatives, I have not looked closely at the code in a long while.
    2) Loading one applet in another is possible, but not easy.
    3) I half expect that each new Java micro-version will ruin it.

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

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

Maybe you are looking for