Dynamically Loading a Class with Parameters

Hi,
I'm working on small program during my spare time and I have run into a problem. I have one abstract class (Foo) which is extended by several other subclasses (subFoo1, subFoo2). I am trying to avoid making a whole host of if statements depending on user input by coding in dynamic class loading.
The newInstance() method I've read about works well except that it does not accept arguments, something that I sorely need:
Foo a = Class.forName(input).asSubclass(Foo.class).newInstance();The other method works for creating the objects but I get an error:
Class foo = Class.forName(input);
Constructor cons = cs.getConstructor(new Class[]{String.class, Long.TYPE});
Object a = cons.newInstance(new Object[]{ FooString, FooInt});
a.method()
cannot find symbol
symbol : method(java.math.BigDecimal)
location : java.lang.ObjectI can understand the problem that the new 'Object' can't find the methods of 'foo', but i don't know how to solve the problem.

Object a = cons.newInstance(new Object[]{ FooString, FooInt});
a.method();That isn't very strange, is it? a is an Object, and class Object doesn't have the method you're calling. You have to cast it to a Foo:
Foo a = (Foo)cons.newInstance(new Object[]{ FooString, FooInt});
a.method();

Similar Messages

  • Spry Tabbed panels + Progressive Enhancement and Dynamic Loading of Content With Spry

    Is there any way to combine tabbed panels together with "Progressive Enhancement and Dynamic Loading of Content With Spry"?
    Visit: http://labs.adobe.com/technologies/spry/articles/best_practices/progressive_enhancement.ht ml#updatecontent
    And click on the "Using Spry.Utils.updateContent()"
    The 3rd example shows how to use a fade transition whenever the content changes.
    I already have tabbed panels. My menu contains buttons (on tabs) and my Content div contains the panels.
    Tabs code;
    <ul class="TabbedPanelsTabGroup">
              <li class="TabbedPanelsTab">
                   <table class="Button"  >
                        <tr>
                        <td style="padding-right:0px" title ="Home">
                        <a href="javascript:TabbedPanels1.showPanel(1);" title="Home" style="background-image:url(/Buttons/Home.png);width:172px;height:75px;display:block;"><br/></a>
                        </td>
                        </tr>
                   </table>
              </li>
    etc
    etc
    etc
    and the panel code:
    <div class="TabbedPanelsContent" id="Home">
         CONTENT
    </div>
    I hoped i can use the example code from the link into my tabbed panels.
    I thought this code:
    onclick="FadeAndUpdateContent('event', 'data/AquoThonFrag.html'); return false;"
    could be added to the tab code like this:
    <a href="javascript:TabbedPanels1.showPanel(1);" onclick="FadeAndUpdateContent('event', 'data/AquoThonFrag.html'); return false;" title="Home" style="background-image:url(/Buttons/Home.png);width:172px;height:75px;display:block;"><br/></a>
    But the content doesnt fade...
    I know i need to change the header etc.
    The following is from the link:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:spry="http://ns.adobe.com/spry">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Aquo Events</title>
    <script src="../../../includes/SpryEffects.js" type="text/javascript"></script>
    <script src="../../../includes/SpryData.js" type="text/javascript"></script>
    <script type="text/javascript">
    <!--
    function FadeAndUpdateContent(ele, url)
    try {
         Spry.Effect.DoFade(ele,{ duration: 500, from: 100, to: 0, finish: function() {
              Spry.Utils.updateContent(ele, url, function() {
                        Spry.Effect.DoFade(ele,{ duration: 500, from: 0, to: 100 });
    }catch(e){ alert(e); }
    -->
    </script>
    <style type="text/css">
    /* IE HACK to prevent bad rendering when fading. */
    #event { background-color: white; }
    </style>
    </head>
    So i changed my header etc, put the SpryEffects.js and SpryData.js into position and nothing changed...
    Is there a way to keep my tabbed panel (or change as less as possible) and let
    A. The fade work
    B. The loading work.
    The problem now is that it loads all pages instead of only the home. Therefore i wanted this Progressive Enhancement.
    And the fading part is just because its nice...

    It doesnt show in the post but off course i changed this link;
    "data/AquoThonFrag.html"
    into;
    "javascript:TabbedPanels1.showPanel(1);"
    I must say i dont know if this even works...

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

  • Can I dinamicly load a class with custom class loader ?

    Can I dinamicly load a class with custom class loader ?

    Hi,
    I was wondering if you found answer to your question, and also were you using your custom class loader inside a signed applet as I am in a similar situation, and was wondering if you could help me. An example would be great...
    Thanks a lot.
    Regards.

  • Dynamically load content based on parameters

    Hi guys,
    I have a got a CQ design question here:
    We are building a site which will render various header, footer, list of products and some sections of the main body depending on a set of parameters.
    There are over 300 variations of these parameters, therefore we need to create a machnism which helps to determine what content/page to render at runtime.
    We have thought about couple solutions but still not having a clear idea how they will work in CQ:
    1. Use good old queryString, get the parse the queryString, then in the main jsp page, add some logic and decide which jsp to page to include. But this means we will need potentially hundreds if not thousands of jsp pages to render different content.
    2. Use dynamic selector to include dynamic content. But does that eliminate the need of hundreds of jsp pages?
    Also, in CQ, what is the best practice to store these parameters in http session? Or should they be stored in sling http session instead?
    Many thanks!!!

    If your page consists of a combination of distinct building blocks, and for each building block you have a small number a variantions (3-5), you could use SSI on the dispatcher webserver to build the complete page. Then each individual building block can be cached at the dispatcher, reducing the load on CQ5 publishing dramatically.
    cheers,
    Jörg

  • Generic classes with parameterized super class and interface

    Hello.
    I'm trying to write a generic class that looks like the following pseudo-code.
    public interface Interface {
        public Interface getSibling(...);
    public class Klass {...}
    public class MyKlass<T extends Klass, T2 extends Interface>
            extends T implements T2 {
        public T2 getSibling(...) {
            return this;
    }where Interface and Klass each have various extensions.
    I came across this problem, or challenge, while writing classes for testing my EJBs. I tried and failed various attempts.
    Is it possible to write generic classes of this nature in Java?
    If so, please tell me and others who are like me.
    Thanks in advance.

    No. That would not work.
    Beside being forbidden by the compiler, to my understanding, it cannot be done in theory either, as the parameterized types get bound at instantiation time and are not available for static reference, which both extends and implements require.

  • Customized SSLSocketFactory dynamically loading TrustManager instance with updated truststore

    When I am making LDAPS connection, I would like the LDAPS client be authenticated with latest updated CA certificate in the truststore.
    Here is what I am trying to do:
    // Set up the environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
      "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
    // Specify the socket factory
    env.put("java.naming.ldap.factory.socket", "MySSLSocketFactory");
    // Create the initial context
    DirContext ctx = new InitialDirContext(env);
    Defining the MySSLSocketFactory class here:
    import com.vormetric.server.ServiceLocator;
    import com.vormetric.server.sdk.config.IConfigUtil;
    import com.vormetric.server.sdk.config.LdapException;
    import org.apache.log4j.Logger;
    import javax.net.SocketFactory;
    import javax.net.ssl.*;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.*;
    public class MySSLSocketFactory extends SSLSocketFactory {
       private static Logger logger = Logger.getLogger(MySSLSocketFactory.class);
       public static final String TRUST_STORE_FILE = "server.truststore";
       private static MySSLSocketFactory factory;
       private SSLSocketFactory sslsocket = null;
       private SSLContext sslContext;
       static private String ldapHost;
       private static String domainName;
       private String trustStore;
       //private ExtendedSSLSession sess;
       public MySSLSocketFactory() {
       try {
      IConfigUtil svrCfg = ServiceLocator.getConfigUtilInstance();
       trustStore = svrCfg.getCGSSConfDir() + TRUST_STORE_FILE;
      File file = new File(trustStore);
       if (!file.exists()) {
       throw new LdapException(
       "Trust store non-exists! Configure ldaps settings first.");
       sslContext = getSSLContext(trustStore, domainName);
       //sslContext.setSocketFactory(SSLSocketFactoryImpl.getDefault());
       sslsocket = sslContext.getSocketFactory();
      } catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
       @Override public String[] getDefaultCipherSuites() { return sslsocket.getDefaultCipherSuites(); }
       @Override public String[] getSupportedCipherSuites() { return sslsocket.getSupportedCipherSuites(); }
       public static synchronized SocketFactory getDefault() {
       if(factory == null){
       factory = new MySSLSocketFactory();
       return factory;
       @Override
       public Socket createSocket(Socket socket, String host, int port, boolean bln) throws
       IOException {
       return sslsocket.createSocket(socket, host, port, bln);
       @Override
       public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
       return sslsocket.createSocket(host,port);
       @Override
       public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
       throws IOException, UnknownHostException {
       return sslsocket.createSocket(host, port, localHost, localPort);
       @Override
       public Socket createSocket(InetAddress host, int port) throws IOException {
       return sslsocket.createSocket(host,port);
       @Override
       public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort)
       throws IOException {
       return sslsocket.createSocket(host, port, localAddress, localPort);
       public SSLContext getSSLContext(String trustStore, String domainName)
       throws Exception {
      TrustManager[] trustManagers = new TrustManager[] { new ReloadableX509TrustManager(this.trustStore, this.domainName)
       //SSLContext sslContext = new SSLContextImpl.TLS12Context();
       SSLContext sslContext = SSLContext.getInstance("TLSv1.2", "SunJSSE");
      sslContext.init(null, trustManagers, null);
       return sslContext;
       public static void setDomainName(String name) {
       domainName = name;
       public static String getSsContext() {
       return domainName;
    But here is the problem whenever trying to make LDAPS connection, I am getting the following exceptions with JDK1.7.0_72:
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1) Caused by: java.net.SocketException: Unconnected sockets not implemented
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at javax.net.SocketFactory.createSocket(SocketFactory.java:125)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at java.lang.reflect.Method.invoke(Method.java:606)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   at com.sun.jndi.ldap.Connection.createSocket(Connection.java:307)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   at com.sun.jndi.ldap.Connection.<init>(Connection.java:203)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   ... 59 more
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1) Caused by: java.lang.UnsupportedOperationException
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   at javax.net.SocketFactory.createSocket(SocketFactory.java:123)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   ... 65 more
    Please let me know what I should do to get over this exception.
    Thanks a lot.
    yilicaus

    When I am making LDAPS connection, I would like the LDAPS client be authenticated with latest updated CA certificate in the truststore.
    Here is what I am trying to do:
    // Set up the environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
      "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
    // Specify the socket factory
    env.put("java.naming.ldap.factory.socket", "MySSLSocketFactory");
    // Create the initial context
    DirContext ctx = new InitialDirContext(env);
    Defining the MySSLSocketFactory class here:
    import com.vormetric.server.ServiceLocator;
    import com.vormetric.server.sdk.config.IConfigUtil;
    import com.vormetric.server.sdk.config.LdapException;
    import org.apache.log4j.Logger;
    import javax.net.SocketFactory;
    import javax.net.ssl.*;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.*;
    public class MySSLSocketFactory extends SSLSocketFactory {
       private static Logger logger = Logger.getLogger(MySSLSocketFactory.class);
       public static final String TRUST_STORE_FILE = "server.truststore";
       private static MySSLSocketFactory factory;
       private SSLSocketFactory sslsocket = null;
       private SSLContext sslContext;
       static private String ldapHost;
       private static String domainName;
       private String trustStore;
       //private ExtendedSSLSession sess;
       public MySSLSocketFactory() {
       try {
      IConfigUtil svrCfg = ServiceLocator.getConfigUtilInstance();
       trustStore = svrCfg.getCGSSConfDir() + TRUST_STORE_FILE;
      File file = new File(trustStore);
       if (!file.exists()) {
       throw new LdapException(
       "Trust store non-exists! Configure ldaps settings first.");
       sslContext = getSSLContext(trustStore, domainName);
       //sslContext.setSocketFactory(SSLSocketFactoryImpl.getDefault());
       sslsocket = sslContext.getSocketFactory();
      } catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
       @Override public String[] getDefaultCipherSuites() { return sslsocket.getDefaultCipherSuites(); }
       @Override public String[] getSupportedCipherSuites() { return sslsocket.getSupportedCipherSuites(); }
       public static synchronized SocketFactory getDefault() {
       if(factory == null){
       factory = new MySSLSocketFactory();
       return factory;
       @Override
       public Socket createSocket(Socket socket, String host, int port, boolean bln) throws
       IOException {
       return sslsocket.createSocket(socket, host, port, bln);
       @Override
       public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
       return sslsocket.createSocket(host,port);
       @Override
       public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
       throws IOException, UnknownHostException {
       return sslsocket.createSocket(host, port, localHost, localPort);
       @Override
       public Socket createSocket(InetAddress host, int port) throws IOException {
       return sslsocket.createSocket(host,port);
       @Override
       public Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort)
       throws IOException {
       return sslsocket.createSocket(host, port, localAddress, localPort);
       public SSLContext getSSLContext(String trustStore, String domainName)
       throws Exception {
      TrustManager[] trustManagers = new TrustManager[] { new ReloadableX509TrustManager(this.trustStore, this.domainName)
       //SSLContext sslContext = new SSLContextImpl.TLS12Context();
       SSLContext sslContext = SSLContext.getInstance("TLSv1.2", "SunJSSE");
      sslContext.init(null, trustManagers, null);
       return sslContext;
       public static void setDomainName(String name) {
       domainName = name;
       public static String getSsContext() {
       return domainName;
    But here is the problem whenever trying to make LDAPS connection, I am getting the following exceptions with JDK1.7.0_72:
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1) Caused by: java.net.SocketException: Unconnected sockets not implemented
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at javax.net.SocketFactory.createSocket(SocketFactory.java:125)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    2015-03-02 13:23:37,563 ERROR [stderr] (http-/0.0.0.0:8445-1)   at java.lang.reflect.Method.invoke(Method.java:606)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   at com.sun.jndi.ldap.Connection.createSocket(Connection.java:307)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   at com.sun.jndi.ldap.Connection.<init>(Connection.java:203)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   ... 59 more
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1) Caused by: java.lang.UnsupportedOperationException
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   at javax.net.SocketFactory.createSocket(SocketFactory.java:123)
    2015-03-02 13:23:37,564 ERROR [stderr] (http-/0.0.0.0:8445-1)   ... 65 more
    Please let me know what I should do to get over this exception.
    Thanks a lot.
    yilicaus

  • Dynamic loading of a class at runtime with known inheritance

    Hi,
    I am trying to dynamically load a class during runtime where I know that the class implements a particular interface 'AInterface'. Also, this class may be linked to other classes in the same package as that class, with their implementations/extensions given in their particular definitions.
    The class is found by using a JFileChooser to select the class that implements 'AInterface', and loaded up.
    Because the name of the class can be practically anything, my current approach only works for certain classes under the package 'Foo' with classname 'Bar'. Some names have been changed to keep it abstract.
    private AInterface loadAInterface(URL url) throws Exception {
         URL[] urls = { url };
         // Create a new class loader with the directory
         URLClassLoader cl = new URLClassLoader(urls);
         // Load in the class
         Class<?> cls = cl.loadClass("Foo.Bar");
         return (AInterface) cls.newInstance();
    }As you can see, all that is being returned is the interface of the class so that the interface methods can be accessed. My problem is that I don't know what the class or package is called, I just know that the class implements AInterface. Also note that with this approach, the class itself isn't selected in the JFileChooser, rather the folder containing Foo/Bar.class is.

    ejp wrote:
    The class is found by using a JFileChooser to select the class that implements 'AInterface', and loaded up.
    Also note that with this approach, the class itself isn't selected in the JFileChooser, rather the folder containing Foo/Bar.class is.These two statements are mutually contradictory...My apologies, I worded that wrong. My current approach (the one given in the code) selects the root package folder. However, what I want to be able to do, is to simply select a single class file. The current code just makes some assumptions so that I can at least see results in the program.
    As you said, if the root of the package hierarchy is known, then this could be achieved. The problem is that the user either selects the package root or the AInterface class, but not both.
    Is there a way to get package details from a .class file to be used in the actual loading of the class?

  • Help on dynamically loading of simple classes - ClassLoader

    Hello,
    does somebody know how to load simple classes with java.lang.ClassLoader in a stateless session bean running on SneakPreview 6.40?
    i found many solutions for j2ee servers on the net but no one works. i always get a ClassNotFoundException but i can read the class file to a byte array.
    this is one way i tried to solve the problem:
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class aClass = Class.forName(strClassName, true, loader);
    hopefully someone can help me,
    thanks
    erich

    Hi Erich,
    for such a kind of problems (not knowing for sure where the classloader is looking for the class) I am used to use http://www.sysinternals.com/ntw2k/source/filemon.shtml
    Just write <i>Class.forName("ABC123", true, loader);</i> and then you can check the places where the classloader is looking for this ABC123 class...
    Hope it helps
    Detlev

  • Unloading loaded SWF classes

    This is a fairly complicated issue so I'll try to explain it as best I can.
    The first part is that I am downloading a SWF from a server that has a bunch of exported images in it. I am doing a lookup of the class names for these images then using that to load the data into the application. Later on down the line it is possible to download a separate SWF that has images in the same format with overlapping names.
    The issue here is that when loading the second SWF with duplicate names it doesn't overwrite the data as one might expect, it uses whatever was loaded first. So I need to know if it's possible to either make it overwrite the classes with the new data or throw them away before loading the new SWF so the old ones don't get in the way. Is this possible at all? If not I suppose we could change the name of all of the assets so they are guaranteed to be unique but that would be a massive headache that I want to avoid at all costs.

    I have my ways I'm Just looking up all of the available classes in the SWF and then getting the class data out of it and using that to load the images into the app.
    EDIT: I sort of see what the problem is. The SWF files are being loaded into the same application domain so I assume that somehow limits loading multiple classes with the same name. So maybe I have to load each SWF into a new ApplicationDomain instead of using the main apps domain?

  • How do I dynamically load a SWF that was compiled from an Fla with a linked external class file

    I am dynamically loading external SWFs in a Main Fla in response to clicks on a menu.
    The loading code is standard and works fine for all of the SWFs except one. When I try to load it I get the following error:
    Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
    I am certain that the URL to the problem SWF is correct. The SWF itself doesn't load any other SWFs or images.
    The problem SWF is linked to an external class file and compiled with it.
    i.e. in the properties panel of the main timeline of the problem SWF's Fla I have entered the path to the external class.
    1. there is no problem compiling this SWF with the class (it works fine by itself)
    2. if I remove the external class from the properties panel and don't use it the resulting SWF imports without a problem into the Main Fla mentioned before
    So the problem seems to be the fact that the external class is linked in the properties panel. Is this a path problem?
    Would appreciate any suggestions,
    Thanks!

    despite what you say, that loaded swf most likely is loading something and that's the cause of the error.
    you could test that by putting the main swf's embedding html file in the same directory with problematic swf.  if the problem is as explained above, you'll have no problem when the main html is in the same directory with the loaded swf.

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

  • Error editing task sequence: Failed to load dynamic properties for class "SMS_TaskSequence_ApplyWindowsSettingsAction" From XML into WMI

    I've started getting an intermittent error editing my Windows 7 OSD task sequence.  Sometimes I can open the TS to edit, but when I try to apply changes I get the error.  Other times I get the error when trying to open the TS.  If I try again
    right away, I still get the error, but if I wait a few minutes and try again sometimes it will open the TS. 
    The error reads:
    ConfigMgr Error Object:instance of SMS_Extended Status{Description = "Failed to load dynamic properties for class \"SMS_TaskSequence_ApplyWindowsSettingsAction\" from XML into WMI";Error Code = 2147943746;File = "e:\\qfe\\nts\\sms\\siteserver\\sdk_provider\\smsprov\\ssptspackage.cpp";Line = 3454;Operation = "ExecMethod";ParameterInfo = "SMS_TaskSequencePackage";ProviderName = "WinMgmt";StatusCode = 2147749889;}
    Coinciding with this error, I show the following entries in the TaskSequenceProvider.log file: 
    [PID: 7608] Invoking method SMS_TaskSequence.LoadFromXml
    TaskSequenceProvider
    Failed to protect memory buffer, hr=0x80070542
    TaskSequenceProvider
    Failed to load dynamic properties for class "SMS_TaskSequence_ApplyWindowsSettingsAction" from XML into WMI 0x80070542 (2147943746)
    TaskSequenceProvider
    Failed to load node Apply Windows Settings from XML into WMI 0x80070542 (2147943746)
    TaskSequenceProvider
    Failed to load children steps for node "PostInstall" from XML 0x80070542 (2147943746)
    TaskSequenceProvider
    Failed to load children steps for node "Execute Task Sequence" from XML 0x80070542 (2147943746)
    TaskSequenceProvider
    Failed to load children steps for node "" from XML 0x80070542 (2147943746)
    TaskSequenceProvider
    Failed to load XML for the task sequence into WMI 0x80070542 (2147943746)
    TaskSequenceProvider
    [PID: 7608] Done with method SMS_TaskSequence.LoadFromXml
    TaskSequenceProvider
    Setting status complete:  status code = 0x80070542; Failed to load dynamic properties for class "SMS_TaskSequence_ApplyWindowsSettingsAction" from XML into WMI
    TaskSequenceProvider
    I exported the task sequence and checked in "object.xml" for the "ApplyWindowsSettingsAction", to see if there was something odd in the xml, but I don't find anything that jumps out as being wrong.  Here's the section of XML for
    that step.  I've removed identifying info, and replaced it with a generic term in bold.
    <step type="SMS_TaskSequence_ApplyWindowsSettingsAction" name="Apply Windows Settings" description="" runIn="WinPE" successCodeList="0" runFromNet="false"><action>osdwinsettings.exe /config</action><defaultVarList><variable name="OSDLocalAdminPassword" property="AdminPassword"></variable><variable name="OSDComputerName" property="ComputerName">%_SMSTSMachineName%</variable><variable name="OSDProductKey" property="ProductKey"></variable><variable name="OSDRandomAdminPassword" property="RandomAdminPassword">false</variable><variable name="OSDRegisteredOrgName" property="RegisteredOrgName">COMPANY NAME</variable><variable name="OSDRegisteredUserName" property="RegisteredUserName">COMPANY NAME</variable><variable name="OSDServerLicenseConnectionLimit" property="ServerLicenseConnectionLimit">5</variable><variable name="OSDTimeZone" property="TimeZone">Central Standard Time</variable></defaultVarList></step><step type="SMS_TaskSequence_ApplyNetworkSettingsAction" name="Apply Network Settings" description="" runIn="WinPEandFullOS" successCodeList="0" runFromNet="false"><action>osdnetsettings.exe configure</action><defaultVarList><variable name="OSDDomainName" property="DomainName">DOMAIN.COM</variable><variable name="OSDJoinPassword" property="DomainPassword"></variable><variable name="OSDJoinAccount" property="DomainUsername">DOMAIN ACCOUNT</variable><variable name="OSDEnableTCPIPFiltering" property="EnableTCPIPFiltering" hidden="true">false</variable><variable name="OSDNetworkJoinType" property="NetworkJoinType">0</variable><variable name="OSDAdapterCount" property="NumAdapters" hidden="true">0</variable></defaultVarList></step>
    Is there any other log I should check for a clue on this issue?  What could be causing this error?

    Thanks for sharing that!  I tend to save contacting MS support until after I've exhausted other options.  I'm always afraid that I'll spend the $500 to open a case and then it turns out to be something simple that I would have found if I had just
    kept working on it myself a little longer.
    It looks like that link is for an update released in February as KB3023562.  I downloaded and installed it. I'll try opening/editing/saving the task sequence a few times today to see if the issue is resolved.  
    After I had already installed it, I thought to look up that update in configmgr.  The update is listed as superseded by 2 other updates.  The newest of those is KB3046049, which just installed last night with the other March patches, so it's possible
    that I didn't need to install KB3023562 after all.  

  • Dynamic invocation of javac with custom class path.

    To all the Java Gurus out there,
    Consider the following classes:
    XYZ/test/TestUtil.java
    package test;
    class TestUtil {
      void useMe() {
    }ABC/test/Test.java
    package test;
    public class Test {
      public static void main(String[] args) {
        TestUtil t = new TestUtil();
         t.useMe();
    }The class Test uses package private access to the TestUtil.useMe() method. Then the Test class is packaged into test.jar and the TestUtil class is packaged into testutil.jar.
    Our application uses a custom class loader architecture where the test.jar is loaded by class loader "X" and testutil.jar is loaded by class loader "Y". Also Y is the parent class loader of X. When the main() of Test class is run it results into IllegalAccessException as the package private method is being accessed from different class loaders.
    We are currently using a dynamic way to detect the dependency between test.jar and testutil.jar and generating the classpath argument to the "javac" ant task which dyncamically invokes the sun.tools.javac.Main class. So while compiling Test class the following command line is generated:
    javac -classpath XYZ/testutil.jar Test.java
    It compiles fine assuming that the Test class and the TestUtil class are loaded by the same class loader but at runtime this fails.
    Is there a way to make "javac" use our runtime class loader architecture to instead of static classpath, so that the access violation is captured at compile time?
    Any help is appreciated.
    Ravi
    PS: If this is not the right forum please point me to the right place to post this questions.

    Not that I'm aware of - the Java Language is designed to be platform-independent so absolute file paths which is a specific feature of various file systems would naturally not to be mixed up with the object-oriented hierarchy structure.
    Just like a compiler wouldn't check if a file exists in
    new File("<FilePath>")I don't think you can get compile-time checks for what you have wanted.
    Hope this helps~
    Alex Lam S.L.

Maybe you are looking for

  • SharePoint 2010 Excel Services with SQLserver 2012 cubes

    I have two tier sharepoint 2010 enterprise setup 1)wfe  and app server 2) sqlserver I also have a sqlserver 2012 which hosts all our BI cubes . is it possible to connect excel (office 2010)  to sql 2012 BI and save that in my sharepoint 2010 server 

  • BUG?  ViewObject contains more than one Row with equal Key objects

    JDeveloper 10.1.2.1 build 1913 JClient app aView ----bView --------cView ------------dView BEFORE: cView's detail row set contains two dViewRowImpl rows, as expected: row 0: key = 100 row 1: key = 101 ACTION: An attribute, X, in dView is modified by

  • "Save as"  Finder Window

    My comment is coming a little late in the game but it's something that has bugged me since OS 9. If I remember way back when, when I saved a document with the "Save as" command, one would get a drop down window and when one clicked Save, the file wou

  • Changing Administrators Short Code

    Hi. Just set up my new imac and want to change the short code. I do not like the short code that comes up as my user folder name in the user directory. I am the administrator / main user so i cant delete my own account to create a new one as the onli

  • 11g How to programmatically access Calendar Rules

    Hi guys, I use BPM 11g and I'm trying to programmatically access calendar rules configuration for the organization in order to display labor dates in ADF task flow using Simple Expression like: now + 2 business days. Has anyone done this on 11g? Than