Class loading and reflection

Hi,
I am trying to use a custom class loader to dynamically load Java classes so that I can get some info (e.g. methods) about the classes via reflection. My problem is that my class loader is written to load Java core classes (i.e. java.lang, java.util, etc.), which as far as I know cannot be done since ClassLoader.defineClass() disallows such attempts. The reason I need to load the core classes is because my program extensively uses Java 5 features (thus have to run using JRE version 5) but need access to Java 1.4 classes in order to get the class' info via reflection.
I am almost out of ideas and thought that what I am trying to do might be achievable if there is a way where I can use the reflection APIs without loading a class first -- I doubt that this can be done using standard Java API, but I will appreciate it if anyone knows any tools/libraries that can do this or if anyone can give other suggestions to solve my problem.
Thanks,
Hendrik

slackiz wrote:
Hi,
I am trying to use a custom class loader to dynamically load Java classes so that I can get some info (e.g. methods) about the classes via reflection. My problem is that my class loader is written to load Java core classes (i.e. java.lang, java.util, etc.), which as far as I know cannot be done since ClassLoader.defineClass() disallows such attempts. The reason I need to load the core classes is because my program extensively uses Java 5 features (thus have to run using JRE version 5) but need access to Java 1.4 classes in order to get the class' info via reflection.
Just to be clear in case someone else in the future finds this....
You cannot and must not attempt to "load" core classes from different VM versions into the same VM.
It doesn't matter what the reason is it is will always be wrong.
Conversely I am guessing the OP just wants to look/interpret the classes versus actually loading them. So BCEL should work or one could always roll their own class file reader.

Similar Messages

  • Custom class loader and local class accessing local variable

    I have written my own class loader to solve a specific problem. It
    seemed to work very well, but then I started noticing strange errors in
    the log output. Here is an example. Some of the names are in Norwegian,
    but they are not important to this discussion. JavaNotis.Oppstart is the
    name of my class loader class.
    java.lang.ClassFormatError: JavaNotis/SendMeldingDialog$1 (Illegal
    variable name " val$indeks")
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at JavaNotis.Oppstart.findClass(Oppstart.java:193)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
    at JavaNotis.SendMeldingDialog.init(SendMeldingDialog.java:78)
    at JavaNotis.SendMeldingDialog.<init>(SendMeldingDialog.java:54)
    at JavaNotis.Notistavle.sendMelding(Notistavle.java:542)
    at JavaNotis.Notistavle.access$900(Notistavle.java:59)
    at JavaNotis.Notistavle$27.actionPerformed(Notistavle.java:427)
    JavaNotis/SendMeldingDialog$1 is a local class in the method
    JavaNotis.SendMeldingDialog.init, and it's accessing a final local
    variable named indeks. The compiler automatically turns this into a
    variable in the inner class called val$indeks. But look at the error
    message, there is an extra space in front of the variable name.
    This error doesn't occur when I don't use my custom class loader and
    instead load the classes through the default class loader in the JVM.
    Here is my class loading code. Is there something wrong with it?
    Again some Norwegian words, but it should still be understandable I hope.
         protected Class findClass(String name) throws ClassNotFoundException
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         private byte[] loadClassData(String name) throws ClassNotFoundException
             ByteArrayOutputStream ut = null;
             InputStream inn = null;
             try
                 JarEntry klasse = arkiv.getJarEntry(name.replace('.', '/')
    + ".class");
                 if (klasse == null)
                    throw new ClassNotFoundException("Finner ikke klassen "
    + NOTISKLASSE);
                 inn = arkiv.getInputStream(klasse);
                 ut = new ByteArrayOutputStream(inn.available());
                 byte[] kode = new byte[4096];
                 int antall = inn.read(kode);
                 while (antall > 0)
                     ut.write(kode, 0, antall);
                     antall = inn.read(kode);
                 return ut.toByteArray();
             catch (IOException ioe)
                 throw new RuntimeException(ioe.getMessage());
             finally
                 try
                    if (inn != null)
                       inn.close();
                    if (ut != null)
                       ut.close();
                 catch (IOException ioe)
         }I hope somebody can help. :-)
    Regards,
    Knut St�re

    I'm not quite sure how Java handles local classes defined within a method, but from this example it seems as if the local class isn't loaded until it is actually needed, that is when the method is called, which seems like a good thing to me.
    The parent class is already loaded as you can see. It is the loading of the inner class that fails.
    But maybe there is something I've forgotten in my loading code? I know in the "early days" you had to do a lot more to load a class, but I think all that is taken care of by the superclass of my classloader now. All I have to do is provide the raw data of the class. Isn't it so?

  • Dynamic class loading and Casting

    Hi guys,
    spent lots of time trying to figure out how to do one thing with no luck, hope anybody can help me here. Here is what I have:
    I need to create a new object, I have dynamic variable of what kind of an object I need:
    sObjectType = "Article";
    ItemObject oItem = Item.init(1000, 1);           
    oItem.ArticleObjectCall();                      // ERROR is here, method does not exist, ArticleObjectCall is method of the Article classItem is a static Class that inits objects
    public class Item {
         public static ItemObject init(String sObjectType) {
                  ItemObject oClass = Class.forName("com.type." + sObjectType).newInstance();
                  return oClass;
    }Below are the 2 classes Article and ItemObject
    Article
    package com.type;
    public class Article extends ItemObject {     
         public void ArticleObjectCall() {
              System.out.println("Article Hello");
    ItemObject
    public class ItemObject {
         public ItemObject() {          
    }

    Ajaxian wrote:
    This is a method INIT, I am dynamically including class com.type.Article , Article extends ItemObject, I am casting new instance of Article to (ItemObject) to return a proper type but later when I try to call oClass object which is I believe my Article class, I get an error. None of which answers my question, yet it does show that you are thoroughly confused...
    String x = "blub";
    Object y = x;
    System.out.println(y.length); // We both know y is a string, but the compiler does not. => ErrorThe compiler enforces the rules of a static type system, your question is quite explicitly about dynamism, which is not without reason the antonym to statics. If you load classes dynamically, you need to use reflection to invoke their methods.
    With kind regards
    Ben

  • Dynamic Class Loading and Stubs

    How Dynamic Class Loading is used on Java RMI, since stubs are generated on clients using Reflection API?
    I was reading Dynamic code downloading using JavaTM RMI (http://java.sun.com/javase/6/docs/technotes/guides/rmi/codebase.html), it seems to be out of date.
    For example, "The client requests the class definition from the codebase. The codebase the client uses is the URL that was annotated to the stub instance when the stub class was loaded by the registry. Back in step 1, the annotated stub for the exported object was then registered with the Java RMI registry bound to a name."

    "Enhancements in J2SETM 5.0
    Dynamic Generation of Stub Classes
    This release adds support for the dynamic generation of stub classes at runtime, obviating the need to use the Java(tm) Remote Method Invocation (Java RMI) stub compiler, rmic, to pregenerate stub classes for remote objects. *Note that rmic must still be used to pregenerate stub classes for remote objects that need to support clients running on _earlier versions_.*
    When an application exports a remote object (using the constructors or static exportObject methods(1) of the classes java.rmi.server.UnicastRemoteObject or java.rmi.activation.Activatable) and a pregenerated stub class for the remote object's class cannot be loaded, the remote object's stub will be a java.lang.reflect.Proxy instance (whose class is dynamically generated) with a java.rmi.server.RemoteObjectInvocationHandler as its invocation handler.
    An existing application can be deployed to use dynamically generated stub classes unconditionally (that is, whether or not pregenerated stub classes exist) by setting the system property java.rmi.server.ignoreStubClasses to "true". If this property is set to "true", pregenerated stub classes are never used.
    Notes:
    * If a remote object has pre-5.0 clients, that remote object should use a stub class pregenerated with rmic or the client will get an ClassNotFoundException deserializing the remote object's stub. Pre-5.0 clients will not be able to load an instance of a dynamically generated stub class, because such a class contains an instance of RemoteObjectInvocationHandler, which was not available prior to this release.
    * Prior to the J2SE 5.0 release, exporting a remote object would throw a java.rmi.StubNotFoundException if the pregenerated stub class for the remote object's class could not be loaded. With the added support for dynamically generated stub classes, exporting a remote object that has no pregenerated stub class will silently succeed instead. A user deploying a server application to support pre-5.0 clients must still make sure to pregenerate stub classes for the server's remote object classes, even though missing stub classes are no longer reported at export time. Such errors will instead be reported to a pre-5.0 client when it deserializes a dynamically generated stub class.
    (1) The static method UnicastRemoteObject.exportObject(Remote) is declared to return java.rmi.server.RemoteStub and therefore cannot be used to export a remote object to use a dynamically generated stub class for its stub. An instance of a dynamically generated stub class is a java.lang.reflect.Proxy instance which is not assignable to RemoteStub."
    http://java.sun.com/j2se/1.5.0/docs/guide/rmi/relnotes.html

  • Class loader and verifier

    Hello,
    I am trying to write a application that will be able to load unknown classes and find out their methods and fields. My problem is that i don't know how to extraxt the necessary information(methods, fields) from the classes. The first answer would be probably reflection, but as i've seen from a quick look at its tutorial it can give me only the public methods-fields(i think also private fields but not certain) of a class, but i need also the private and protected methods-fields that the class may have.
    Basically, i need someone to point me to the right direction(class loader-verifier or something) of how to do these things and after that i'll go in depth...
    Thanks in advance,
    Antony

    Reflection, i.e. Class.forName(..).get...(), will give you all you need, including privates. I believe the security policy determines how much access your code gets to privates.

  • Dinamyc class loading and jar files

    I'm new to java. I would like to load some plugins in my application (it's going to be packaged as a jar at the end). I managed to find some dinamyc class loading examples but they search for the classes to load in a directory.
    This is the code:
        public static void main(String[] args) {
            File pluginDirectory = new File("src/pluginsreloaded/plugins");
            if (!pluginDirectory.exists()) {            // the plugin directory does not exist
                System.out.println("The plugins directory does not exist!");           
                return;
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".class");
            String[] pluginFiles = pluginDirectory.list(filter);
            for (int i = 0; i < pluginFiles.length; i++) {
                if (pluginFiles.indexOf("$") == -1) {
    System.out.println("Loading: " + pluginFiles[i].substring(0, pluginFiles[i].length() - 6));
    IPlugin plugin = pm.loadPlugin(pluginFiles[i].substring(0, pluginFiles[i].length() - 6));
    System.out.println(plugin.description());
    protected static IPlugin loadPlugin(String name) {
            // Query the plugin list for the plugin
            PluginFactory _plugin = (PluginFactory) pluginList.get(name);
            if (_plugin == null) {          // the plugin is not loaded
                try {
                    Class.forName("pluginsReloaded.plugins." + name);
                    // The plugin makes an entry in the plugin list
                    // when loaded
                    _plugin = (PluginFactory) pluginList.get(name);
                    if (_plugin == null) {
                        return null;
                } catch (ClassNotFoundException e) {
                    System.out.println("Plugin " + name + " not found!");
            return _plugin.create();
        }IPlugin is an interface. I am using netbeans 5.0. The error I get is this:
    Exception in thread "main" java.lang.NoClassDefFoundError: pluginsReloaded/plugins/plugin1 (wrong name: pluginsreloaded/plugins/plugin1)
            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 sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
            at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
            at java.lang.Class.forName0(Native Method)
            at java.lang.Class.forName(Class.java:164)
            at pluginsreloaded.PluginManager.loadPlugin(PluginManager.java:30)
            at pluginsreloaded.Main.main(Main.java:44)
    Java Result: 1As far as I can see it can't find the class. My question is how can I load the class/where can I find it?
    Thanks.

    You can use the java.util.jar.JarFile class to enumerate the contents of a jar. It's not good practice to search for plugins in this way though. A plugin may well involve serveral classes, which don't all have to be internal. Furthermore its wise to avoid any comitment about the mechaism by which class files are to be fetched. You might want to do it remotely, some time, or load them from a database.
    What seesms to be the standard approach is to put a list of plugin classes into the jar as a text file.
    Plugins for a given purpose usually implement some specified interface, or extend some abstract class to which their objects can be cast once loaded (without this they aren't really much use).
    Say your plugins implment org.myorg.WidgetFactory then you put a list of them, one fully qualified name to a line, in a file or jar entry called META-INF/services/org.myorg.WidgetFactory. You framework picks up all such files from the classpath using ClassLoader.getResources() and loads all the classes whose names if finds, hence you can add new sets of plugins just by adding a new jar or class directory to the class path.

  • Dynamic Class Loading and Unloading

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

  • Problem related to class loader and bootstrap loader

    how class are loaded and how bootstraping please explain it in detail?

    793241 wrote:
    how class are loaded and how bootstraping please explain it in detail?Just to put in different words what previous posters are hinting at; this is not a place to come and get answers when you don't want to do research yourself - it is not even a problem you are having as it has a readily available solution; read and enlighten yourself.

  • EJB Class loader and regular Java files class loader.

    Hi,
    Is the EJB's class loader the same as a "regular" java files class loader OR weblogic
    has 2 class loaders, one for each???
    Thanks,
    les.

    les <[email protected]> wrote:
    Hi,
    Is the EJB's class loader the same as a "regular" java files class loader OR weblogic
    has 2 class loaders, one for each???Yes. Exact classloading architecture depends on which WebLogic version you use. If you
    use 6.x+, you may want to read this article:
    http://www.onjava.com/pub/a/onjava/2001/07/25/ejb.html
    Thanks,
    les.--
    Dimitri

  • What is diff. b/w Class loading and class initializing??

    Hi Guys,
    When we are using final keyword as:
    final static int cout;
    Then class will load but not initialize?
    Could any one explain this??
    Thanks in advance.

    >
    When we are using final keyword as:
    final static int cout;
    Then class will load but not initialize?
    Could any one explain this??
    >
    The class will load but not initialize? Where did you get that from?
    See 4.12.4. final Variables in the Java Language Spec
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4
    >
    A blank final is a final variable whose declaration lacks an initializer.

  • Generic Populating the XML document using Java Class Generator and Reflection

    I am looking for a generic source code in order to convert the data parsed from any tabular text form ( tab delimited for example that maps certain XML Schema created form Database Schema for Oracle.
    I know it is possible to generate XML DTD or XSD from Oracle database table schema by XSU utility from XDK. And also it is possible to create Java source files from an XML DTD or XSD by using XML Clas Generator.
    I believe there must be some generic code that parses tabular text data and converts them to XML format using above mentioned generated Java source files and may be Java reflection mechanism.
    If anyone has any tool or knows any free ware that helps me, I would like to know about it, and I would really appreciate it.

    1. Read the XML file into a DMO object, walk the DOM to find the list, insert your new entry as a child, write the DOM back to a file.
    2. If the XML is not in a file, but in a string, then you can do the same with string input and output.

  • Class loading and Compile time constants

    Hi,
    I am not sure if this is the right place for basic questions. I would appreciate any help.
    From my understanding, the compile time constants are folded into the byte code during compilation. ( E.g. static final int MAX = 10; ). When I access a compile time constant from a different class, I can see that the class that holds the constant is not loaded at all. ( using -verbose:class option )
    Now, my question is, how does JVM access the class that holds the constant without loading it ?! Without the class being loaded, how can the JVM get a binary representation of the same ? What am I missing here ?
    thanks,
    Soumya.

    class A {
      public static final int X = 10;
    class B {
      void foo(int n) {
        switch n {
          case A.X:
            yadda();
    }The value of X (10) from class A is "folded" into the bytecode of class B.

  • Class load and instance memory footprint questions

    Lets say I have CLASS_A that has three members:
    private int a;
    private int b;
    private int c;
    but lets say Class_A has 32 methods manipulating the state of the object.
    For argument sake lets say when CLASS_A is compiled this class (Bytecode) file comes out to be 32Kilobytes.
    Now when my compiler has to load this class it loads the whole 32 kilo class file. but for subsequent instances of CLASS_A will the footprint for each instance be 32 Kilobytes or will it be the 12 (4X3)bytes that are needed to represent the member variables (+ some more bytes to refer to classname or something)?
    I guess my question is does each instance take up 32 Kilobytes?
    Thanks for all replies !

    No, each instance (within the same JVM process) will take up the amount that the instance variables take up, not that plus the instance methods. The implementation code won't get loaded multiple times.

  • Class loader and Byte code verifier

    Can some one tell me what these stuff do ?

    Ask a one line question and you will often get a short but accurate reply.
    These topics and more are discussed in great detail in the JVM specification that you can find here:
    http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html
    Happy reading.

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

Maybe you are looking for

  • How to print smartforms which is comes as result of transactions in queue

    Hi All,       I was working on CRM development based on Pre-Inpsection and Post-Inspection where i am facing some problems in the development work.In this program we have to print Pre-Inspection and Post-Inspection forms through transactions. Once Pr

  • Why is my attachment finder window different

    My finder window has my frequent file folders in the sidebar. When I use mail to send an attachment it's finder window (and Sidebar) usually mimick the finder sidebar. However I noticed my recently added folder in my finder sidebar does not show up i

  • Regarding ALV standarad sort functionality

    Hi All, We are developing the webdynpro ABAP application using ALV functionality which will display the data. Here as per the SAP standard functionality if we click on sort option if there are same values for multiple records in a single column then

  • Fix Err_empty_response

    Why do I continue to periodically get this error. I have cleared all my cookies; deleted the cookies.plist file; emptied trash and yet get this message. I have checked my internet connections wehich are all working.  ; can get into my mail and facebo

  • CA96 update of in-house production time

    Dear PP Gurus , I want to update material master for in-house production time with Routings lead times. The system update processing time (lot dependent) but I want to update the in-house production time (MRP2 view). Can you help me ? Thanks in advan