Dynamic class cast and instanceof

I am looking for a way to dynamically test an object for being of a specific class. The instanceof operator can only be used with literally named classes I understand. So you cannot have something like boolean checkClass( Object o, Class c ) {
   return o instanceof c;
} Is there any way to do something like this by use of the reflection API? The point is that instanceof only works statically, the reference type being tested for being specified at compile time. The question is whether it can be done with a reference type being specified at run-time, ie dynamically.

There is a collection of parameters of various types, which is passed to some client module.
There should be a, say 'checkParam' method for the client, which checks for existence of a certain parameter by its name, and also specified which class the parameter should have. So it should be called like
checkParam( params, "paramName", String.class )I wanted to avoid hard-coded types, but have the class specified as an argument to this method. I feel like there should be some way to accomplish that. What swingfreak intended may be a way.

Similar Messages

  • Can I do dynamic class cast with java SE1.4.2?

    Hi,
    I have some question on dynamic class cast.
    I'm using java SE1.4.2. Suppose I have a method :
    castObjectToSomething(Object o)
    Something s = (Something) o;
    However, I don't know what is the class to cast until runtime. How can I do a runtime class cast?
    I know that java 5.0 have a Class.cast() method which java1.4.2 does not have. But can I do the same stuff by using SE1.4.2?
    Thank You!!!!!
    oh_silly

    There is no sense in wanting to cast to a class that is only known at runtime. Because you can't do anything with such a class during runtime. Even though you could technically retrieve the class name, the method names and the parameter names, you could do nothing with this class as you don't know what it is doing. If you would know what it can do, you would know it also during compile time and then you would know the classname/interface name you want to cast to and can import it and use it reasonably.
    Tell us the requirement that you think you have and we will proof you that you don't need such a requirement.

  • [svn:bz-trunk] 20004: Remove unneeded cast and instanceof check for FlexConfigurable.

    Revision: 20004
    Revision: 20004
    Author:   [email protected]
    Date:     2011-01-28 11:13:07 -0800 (Fri, 28 Jan 2011)
    Log Message:
    Remove unneeded cast and instanceof check for FlexConfigurable.
    No functional change.
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/FactoryDestination.java

  • 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 casting during runtime

    I'm reading parameters for my application from the configuration file. Then in the code I should dynamically during the runtime make class cast:
    (instead of having String in the code, I should cast the object to the class that was
    defined in the configuration file.)
    String tmp = (String) object;
    Could somebody provide an example how can I do this? I have understood I could use reflection API for this problem.

    I am not sure that I understand what you are asking correctly, but it might be something that bothered me some time ago.
    My problem was that I wrote names of Classes (as Stings) into a file, and later wanted to be able to initialize a specific object of the class based on String names that were read from that file.(sorry if this is confusing).
    I was programing a Chess simulator. All figures were subclasses of the class Figure, and were named Peon, Queen...)
    I wanted to make a new Peon object, for every "Peon" String that was read from the file, and to make an new Queen object for every "Queen" in the file and so on.
    I used something like this:
    String objectName = in.readUTF(); //or some other way to get a String
    Figure f = (Figure) Class.forName(objectName).newInstance(); Class.forName(String name) returns a object of class Class that represents all objects of type name.
    And invoking .newInstance() gives you a new object of the class that is being represented by the object of class Class that you invoked .newInstance() on.
    Sorry - migth be confusing again but i think it is correct.
    This call to .newInstance() calls the default no-argument constructor...
    There is no way to call a argument containing constructor with .newInstance()

  • 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

  • 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

  • Dynamic Class cast

    I have an instance of a class as a generic Object and I want to
    get all the methods and fields etc without resorting to too much
    reflection.
    Object o; //i have this
    Class c = o.getClass();
    c myobj = (c)o; //i want to do some casting and not go into getting declared
              //fields and methods and then call them.
    myObj.get(...); //get values from there
    Is it possible or any other way?

    No you can't do that. Basically your question is, can I use reflection without using reflection.

  • Dynamic class casting.

    Hi Friends,
    How do I cast an object dynamically ?
    Here I made a sample example for what I need exactly.
    java.lang.String str = "sample";
    java.lang.Object obj = str;
    Class cls = obj.getClass();
    java.lang.String tmpStr = (cls)obj; // this is an error.
    Instead of casting like (java.lang.String), I wanted to replace "(java.lang.String)" with an variable.
    Any ideas??
    Thanks,
    SK.

    Doesn't make sense to me at all why you think you'd
    need that. You already know you want it to be a
    java.lang.String, because you coded:
    java.lang.String tmpStr = (cls)obj;
    Certainly you and the compiler have to know beforehand
    the object type you need to cast to, so why the fuss?Hi,
    I typed wrongly in my org. note. Sorry about that.
    Actual code snippet looks like this.
    java.lang.String str = "sample";
    java.lang.Object obj = str;
    Class cls = obj.getClass();
    cls tmpStr = (cls)obj; // this is giving me an error.
    I wanted to cast that field dynamically, because upfront I dont know the type of the object.
    In the above example, just for the example sake, I selected a data type "String". Actually I need to cast it based on the type of the object at runtime.
    Thanks,
    SK.

  • Dynamic Class Downloading and EJBs

    Hi all,
    I have one session EJB with business method getObject returning a serializable object which class implements MyObject interface.
    This object's class, named MyObjectImpl, is in only deployed on server within my EAR file.
    I would like my client classpath not containing MyObjectImpl class but only MyObject class (the implemented interface).
    Could you suggest a way to do this, by dynamically downloading implementation class at runtime so I can correcly get casting?
    Thanks in advance
    Fil

    Hi Fil,
    There's no portable way to accomplish this in the Java EE plaform. Java EE requires that all dependent classes needed by a component be packaged with that component at deployment time. Applications are not permitted to dynamically load classes, as this would be both a security issue and a correctness issue. This is true even for clent components, which is why the Java EE platform has a first-class client component called an Application Client. You can find out more about the difference between an Application Client and a stand-alone client in our EJB FAQ.
    https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How do I manage dynamic narrowing casts without instanceof?

    Hi all,
    I need to extract arbitrary Objects from a given Collection and cast them to their original types. The problem is: checking with instanceof won't work for me, because the number of possible types is practically unlimited. Can anybody help?
    Thanks in advance,
    Wolfgang

    I don't think you have to do the cast in the set method. The following code works for me:
    [Main is a simple class with attributes <String a>, <int b> and <Main c>, and has getters for them]
    Note that the code is not nice, it's just a quick-n-dirty test case I wrote in a few minutes.
    Note also that I use Objects in the set method, rather then a String, an Integer and a Main.
          Class mainClass = Class.forName("dynamicinstantiation.Main");
          Constructor ctr = mainClass.getConstructor(new Class[0]);
          // object of class main, not known to the client
          Object main = ctr.newInstance(new Object[0]);
          // fieldvalues to set
          Object a = "String";
          Object b = new Integer(100);
          Object c = new Main();
          // get fields
          Field fldA = main.getClass().getDeclaredField("a");
          Field fldB = main.getClass().getDeclaredField("b");
          Field fldC = main.getClass().getDeclaredField("c");
          fldA.set(main, a);
          fldB.set(main, b);
          fldC.set(main, c);
          // Cast main to Main class, so we;re able to access it's methods
          Main m = (Main)main;
          System.out.println(m.getA());
          System.out.println(m.getB());
          System.out.println(m.getC().getA());
          System.out.println(m.getC().getB());

  • Arrays, Casting and instanceof, Polymorphism

    Having Problems with my programme it compiles but I can't get anything to output when I add a Warden, Rest of code available if you want to compile
    Thankyou
    import java.util.*;
    public class Prison
         private ArrayList <Person> thePersons;
         private String n;
         private int numPrisoners;
         private int numHRPrisoners;
         private int numWardens;
         private int numAllPrisoners;
         private String prisonName;
         private int numAllPrison = (numWardens + numAllPrisoners);
         public Prison (String nameofprison, int numPrisoners, int numHRPrisoners, int numAllPrisoners, int numWardens)
              n = nameofprison;
              numPrisoners = 0;
              numHRPrisoners = 0;
              numAllPrisoners = 0;
              numWardens = 0;
              thePersons = new ArrayList <Person> ();
              public void addPrisoner (Person newPerson)
                   numPrisoners++;
                   numAllPrisoners++;
                   thePersons.add(newPerson);
              public void addHRPrisoner (Person newPerson)
                   numHRPrisoners++;
                   numAllPrisoners++;
                   thePersons.add(newPerson);
              public void addWarden (Person newPerson)
                   numWardens++;     
                   thePersons.add(newPerson);
              public void DisplayPrisoners()
                   System.out.println("Prisoners:");
                        for ( int i =0; i<(numAllPrison); ++i)
                             if (thePersons.get(i) instanceof Prisoner)
                                  System.out.println(thePersons.get(i ).toString());
              public void DisplayWardens()
                   System.out.println("Wardens:");
                        for ( int i =0; i<(numAllPrison); ++i)
                             if (thePersons.get(i) instanceof Warden)
                                  System.out.println(thePersons.get(i ).toString());
              public void DisplayHRPrisoner()
                   System.out.println("High Risk Prisoner:");
                        for ( int i =0; i<(numAllPrison); ++i)
                             if (thePersons.get(i) instanceof HRPrisoner)
                                  System.out.println(thePersons.get(i ).toString());
         //id for later eneter in keyboard     
         public void DisplayPrisonerID(String id)
              Iterator itr = thePersons.iterator();
              while(itr.hasNext())
                   Person nextPersons = (Person)itr.next();
                   if (nextPersons instanceof HRPrisoner)
                        Prisoner p = (Prisoner)nextPersons;
                        if(p.getPrisonerID() == id);
                                  System.out.println(nextPersons);
         public void ReleasePrisoner(int id)
              Iterator itr = thePersons.iterator();
              while(itr.hasNext())
                   Person nextPersons = (Person)itr.next();
                   if (nextPersons instanceof Warden)
                        Prisoner p = (Prisoner)nextPersons;
                        if(p.getDaysLeft() <= 7);
                             System.out.println(nextPersons);
                             System.out.println("Prisoner released");
    This is not 100% complete but the Warden bit is upto where I have a problem
    import java.util.*;
    public class TestPrison2
         public static void main (String[] args)
              //delare everything eg from Prisoner etc
              String thePrisonerID;
              String theName;
              String theSurname;
              String theDOB;
              String theSex;
              int theDaysLeft = 0;
              String prisonerID;
              int daysleft = 0;
              String n;
              int numPrisoners;
              int numHRPrisoners = 0;
              int numWardens = 0;
              int numAllPrisoners = 0;
              int theSecurityLevel;
              String theShareCell;
              String prisonName;
              int wardenRank;
              Prison HMEssex = new Prison("HMEssex",0,0,0,0);
              //public TestPrison ();
              // Prison Boring = new Prison();
              int cmd = 1;
              //While(cmd !=0) menu bit with switchy bit at the end
              while (cmd!=0)
                   System.out.println("1 Add new Warden");
                   System.out.println("2 Add new Prisoner");
                   System.out.println("3 Add HR Prisoner");
                   System.out.println("4 View all Prisoners");
                   System.out.println("5 View all Wardens");
                   System.out.println("6 View Prisoner by ID");
                   System.out.println("7 Release Prisoner");
                   System.out.println("8 Exit");
                   //Scanner bits
                   Scanner kybd = new Scanner(System.in);
                   //make a huge switch statement, delare bollocks
                   //switch (int cmd)
                   cmd = 1;
                   // add Warden
                   System.out.println("Enter selection");
                   cmd = kybd.nextInt();
                   switch(cmd)
                        case 1:
                             String a;
                             System.out.println("Enter Warden name");
                             a = kybd.next();
                             //Warden kybd.next() = new Warden;
                             System.out.println("Enter First Name");
                             String b = kybd.next();
                             System.out.println("Enter Surname");
                             String c = kybd.next();
                             System.out.println("Enter DOB");
                             String d = kybd.next();
                             System.out.println("Enter Gender");
                             String e = kybd.next();
                             System.out.println("Enter Rank");
                             int f = kybd.nextInt();
                             Person warden = new Warden(b,c,d,e,f);
                             HMEssex.addWarden(warden);
                             break;
                        //add a Prisoner
                        case 2:
                             if (numAllPrisoners / 5 < numWardens)
                                  String a;
                                  System.out.println("Enter Prisoner name");
                                  a = kybd.next();
                                  //Prisoner kybd.nextString() = new Prisoner;
                                  System.out.println("Enter PrisonerID");
                                  String b = kybd.next();
                                  System.out.println("Enter First Name");
                                  String c = kybd.next();
                                  System.out.println("Enter Surname");
                                  String d = kybd.next();
                                  System.out.println("Enter DOB");
                                  String e = kybd.next();
                                  System.out.println("Enter Gender");
                                  String f = kybd.next();
                                  System.out.println("Enter days left in prison");
                                  int g = kybd.nextInt();
                                  Prisoner xb = new Prisoner(b,c,d,e,f,g);
                                  HMEssex.addPrisoner (xb);
                             else
                                  System.out.println("Not enough Wardens");
                                  System.out.println("");
                             break;
                        //add a HRPrisoner
                        case 3:
                             if (numHRPrisoners /4 < numWardens)
                                  String a;
                                  System.out.println("Enter Prisoner name");
                                  a = kybd.next();
                                  //HRPrisoner kybd.nextString() = new HRPrisoner;
                                  System.out.println("Enter PrisonerID");
                                  String b = kybd.next();
                                  System.out.println("Enter First Name");
                                  String c = kybd.next();
                                  System.out.println("Enter Surname");
                                  String d = kybd.next();
                                  System.out.println("Enter DOB");
                                  String e = kybd.next();
                                  System.out.println("Enter Gender");
                                  String f = kybd.next();
                                  System.out.println("Enter days left in prison");
                                  int g = kybd.nextInt();
                                  System.out.println("Enter security level");
                                  int h = kybd.nextInt();
                                  System.out.println("Enter if they can share a cell Yes/No");
                                  String i = kybd.next();
                                  HRPrisoner ac = new HRPrisoner(b,c,d,e,f,g,h,i);
                                  HMEssex.addHRPrisoner(ac);
                                  break;
                             else
                                  System.out.println("Not enough Wardens");
                                  System.out.println("");
                        //view Prisoners
                        case 4:
                             HMEssex.DisplayPrisoners();
                             break;
                        //view Wardens     
                        case 5:
                             HMEssex.DisplayWardens();
                             break;
                        //Search for Prisoner by ID               
                        case 6:
                             break;
                        //Release a Prisoner                    
                        case 7:
                             if (daysleft < 7)
                             break;
                        //exit programme
                        case 8:
                             System.exit(0);
                        default:
                        System.out.println("Not an option please choose again");
    }

    Next time post code like this. What your program intends to do and what it does now.
    import java.util.*;
    public class Prison
    private ArrayList <Person> thePersons;
    private String n;
    private int numPrisoners;
    private int numHRPrisoners;
    private int numWardens;
    private int numAllPrisoners;
    private String prisonName;
    private int numAllPrison = (numWardens + numAllPrisoners);
    public Prison (String nameofprison, int numPrisoners, int numHRPrisoners, int numAllPrisoners, int numWardens)
    n = nameofprison;
    numPrisoners = 0;
    numHRPrisoners = 0;
    numAllPrisoners = 0;
    numWardens = 0;
    thePersons = new ArrayList <Person> ();
    public void addPrisoner (Person newPerson)
    numPrisoners++;
    numAllPrisoners++;
    thePersons.add(newPerson);
    public void addHRPrisoner (Person newPerson)
    numHRPrisoners++;
    numAllPrisoners++;
    thePersons.add(newPerson);
    public void addWarden (Person newPerson)
    numWardens++;
    thePersons.add(newPerson);
    public void DisplayPrisoners()
    System.out.println("Prisoners:");
    for ( int i =0; i<(numAllPrison); ++i)
    if (thePersons.get(i) instanceof Prisoner)
    System.out.println(thePersons.get(i ).toString());
    public void DisplayWardens()
    System.out.println("Wardens:");
    for ( int i =0; i<(numAllPrison); ++i)
    if (thePersons.get(i) instanceof Warden)
    System.out.println(thePersons.get(i ).toString());
    public void DisplayHRPrisoner()
    System.out.println("High Risk Prisoner:");
    for ( int i =0; i<(numAllPrison); ++i)
    if (thePersons.get(i) instanceof HRPrisoner)
    System.out.println(thePersons.get(i ).toString());
    //id for later eneter in keyboard
    public void DisplayPrisonerID(String id)
    Iterator itr = thePersons.iterator();
    while(itr.hasNext())
    Person nextPersons = (Person)itr.next();
    if (nextPersons instanceof HRPrisoner)
    Prisoner p = (Prisoner)nextPersons;
    if(p.getPrisonerID() == id);
    System.out.println(nextPersons);
    public void ReleasePrisoner(int id)
    Iterator itr = thePersons.iterator();
    while(itr.hasNext())
    Person nextPersons = (Person)itr.next();
    if (nextPersons instanceof Warden)
    Prisoner p = (Prisoner)nextPersons;
    if(p.getDaysLeft() <= 7);
    System.out.println(nextPersons);
    System.out.println("Prisoner released");
    This is not 100% complete but the Warden bit is upto where I have a problem
    import java.util.*;
    public class TestPrison2
    public static void main (String[] args)
    //delare everything eg from Prisoner etc
    String thePrisonerID;
    String theName;
    String theSurname;
    String theDOB;
    String theSex;
    int theDaysLeft = 0;
    String prisonerID;
    int daysleft = 0;
    String n;
    int numPrisoners;
    int numHRPrisoners = 0;
    int numWardens = 0;
    int numAllPrisoners = 0;
    int theSecurityLevel;
    String theShareCell;
    String prisonName;
    int wardenRank;
    Prison HMEssex = new Prison("HMEssex",0,0,0,0);
    //public TestPrison ();
    // Prison Boring = new Prison();
    int cmd = 1;
    //While(cmd !=0) menu bit with switchy bit at the end
    while (cmd!=0)
    System.out.println("1 Add new Warden");
    System.out.println("2 Add new Prisoner");
    System.out.println("3 Add HR Prisoner");
    System.out.println("4 View all Prisoners");
    System.out.println("5 View all Wardens");
    System.out.println("6 View Prisoner by ID");
    System.out.println("7 Release Prisoner");
    System.out.println("8 Exit");
    //Scanner bits
    Scanner kybd = new Scanner(System.in);
    //make a huge switch statement, delare ********
    //switch (int cmd)
    cmd = 1;
    // add Warden
    System.out.println("Enter selection");
    cmd = kybd.nextInt();
    switch(cmd)
    case 1:
    String a;
    System.out.println("Enter Warden name");
    a = kybd.next();
    //Warden kybd.next() = new Warden;
    System.out.println("Enter First Name");
    String b = kybd.next();
    System.out.println("Enter Surname");
    String c = kybd.next();
    System.out.println("Enter DOB");
    String d = kybd.next();
    System.out.println("Enter Gender");
    String e = kybd.next();
    System.out.println("Enter Rank");
    int f = kybd.nextInt();
    Person warden = new Warden(b,c,d,e,f);
    HMEssex.addWarden(warden);
    break;
    //add a Prisoner
    case 2:
    if (numAllPrisoners / 5 < numWardens)
    String a;
    System.out.println("Enter Prisoner name");
    a = kybd.next();
    //Prisoner kybd.nextString() = new Prisoner;
    System.out.println("Enter PrisonerID");
    String b = kybd.next();
    System.out.println("Enter First Name");
    String c = kybd.next();
    System.out.println("Enter Surname");
    String d = kybd.next();
    System.out.println("Enter DOB");
    String e = kybd.next();
    System.out.println("Enter Gender");
    String f = kybd.next();
    System.out.println("Enter days left in prison");
    int g = kybd.nextInt();
    Prisoner xb = new Prisoner(b,c,d,e,f,g);
    HMEssex.addPrisoner (xb);
    else
    System.out.println("Not enough Wardens");
    System.out.println("");
    break;
    //add a HRPrisoner
    case 3:
    if (numHRPrisoners /4 < numWardens)
    String a;
    System.out.println("Enter Prisoner name");
    a = kybd.next();
    //HRPrisoner kybd.nextString() = new HRPrisoner;
    System.out.println("Enter PrisonerID");
    String b = kybd.next();
    System.out.println("Enter First Name");
    String c = kybd.next();
    System.out.println("Enter Surname");
    String d = kybd.next();
    System.out.println("Enter DOB");
    String e = kybd.next();
    System.out.println("Enter Gender");
    String f = kybd.next();
    System.out.println("Enter days left in prison");
    int g = kybd.nextInt();
    System.out.println("Enter security level");
    int h = kybd.nextInt();
    System.out.println("Enter if they can share a cell Yes/No");
    String i = kybd.next();
    HRPrisoner ac = new HRPrisoner(b,c,d,e,f,g,h,i);
    HMEssex.addHRPrisoner(ac);
    break;
    else
    System.out.println("Not enough Wardens");
    System.out.println("");
    //view Prisoners
    case 4:
    HMEssex.DisplayPrisoners();
    break;
    //view Wardens
    case 5:
    HMEssex.DisplayWardens();
    break;
    //Search for Prisoner by ID
    case 6:
    break;
    //Release a Prisoner
    case 7:
    if (daysleft < 7)
    break;
    //exit programme
    case 8:
    System.exit(0);
    default:
    System.out.println("Not an option please choose again");
    }

  • Dynamic Class Downloading difficulty

    Hi RMI Specialists,
    I am experiencing a possible dynamic class loading issue when attempting to separate the client & server codes across 2 separate Windows (XP & 2000) systems. This exercise (from ch13 of Oreilly�s Learning Java) is made up
    of the following interfaces and classes:
    On the Server side:
    package LearningJavaServer;
    import java.rmi.*;
    import java.util.*;
    public interface RemoteServer extends Remote {
        Date getDate(  ) throws RemoteException;
        Object execute( WorkRequest work ) throws RemoteException;
    package LearningJavaServer;
    import java.rmi.*;
    import java.util.*;
    public class MyServer extends java.rmi.server.UnicastRemoteObject
        implements RemoteServer {
        public MyServer(  ) throws RemoteException { }
        // implement the RemoteServer interface
        public Date getDate(  ) throws RemoteException {
            return new Date(  );
        public Object execute( WorkRequest work ) throws RemoteException {
            return work.execute(  );
        public static void main(String args[]) {
            try {
                RemoteServer server = new MyServer(  );
                Naming.rebind("NiftyServer", server);
            } catch (java.io.IOException e) {
                // problem registering server
    package LearningJavaServer;
    import java.io.*;
    public class Request implements java.io.Serializable {}
    package LearningJavaServer;
    public abstract class WorkRequest extends Request {
        public abstract Object execute(  );
    }On the Client side:
    package LearningJavaClient;
    import java.rmi.*;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;
    public class MyClient {
        public static void main(String [] args)
          throws RemoteException {
            new MyClient( args[0] );
        public MyClient(String host) {
            try {
                RemoteServer server = (RemoteServer)
                    Naming.lookup("rmi://"+host+"/NiftyServer");
                System.out.println( server.getDate(  ) );
                System.out.println(
                  server.execute( new MyCalculation(2) ) );
            } catch (java.io.IOException e) {
                  // I/O Error or bad URL
                     System.out.println( e );
            } catch (NotBoundException e) {
                  // NiftyServer isn't registered
               System.out.println( e );
    package LearningJavaClient;
    import java.rmi.*;
    import java.util.*;
    public interface RemoteServer extends Remote {
        Date getDate(  ) throws RemoteException;
        Object execute( WorkRequest work ) throws RemoteException;
    package LearningJavaClient;
    public class MyCalculation extends WorkRequest {
        int n;
        public MyCalculation( int n ) {
            this.n = n;
        public Object execute(  ) {
            return new Integer( n * n );
    package LearningJavaClient;
    import java.io.*;
    public class Request implements java.io.Serializable {}
    package LearningJavaClient;
    public abstract class WorkRequest extends Request {
        public abstract Object execute(  );
    }Steps to invoke all services on the server side:
    cd C:\Documents and Settings\htran\JavaRMI\build\classes on both systems;
    ( i ) start rmiregistry.
    ( ii ) java -Djava.rmi.server.codebase='http://serverhostname/LearningJavaServer/' -Djava.security.policy="C:\Documents and Settings\htran\.java.policy" -cp . LearningJavaServer.MyServer
    Steps to invoke all services on the client side:
    ( i ) java -Djava.security.policy="C:\Documents and Settings\htran\.java.policy" -cp . LearningJavaClient.MyClient serverhostname
    java.rmi.NotBoundException: NiftyServer
    Or
    ( ii ) java -Djava.rmi.server.codebase='http://clienthostname/LearningJavaClient/' -Djava.security.policy="C:\Documents and Settings\htran\.java.policy" -cp . LearningJavaClient.MyClient serverhostname
    java.rmi.UnmarshalException: Error unmarshaling return; nested exception is:
    java.net.MalformedURLException: no protocol: 'http://clienthostname/LearningJavaClient/'
    Is it possible that this issue could have been caused by either the Request/WorkRequest classes which are present on both system? Likewise, is the location of invoking RMI registry on the server correct?
    Both systems have got their own web servers (http://serverhostname/LearningJavaServer & http://clienthostname/LearningJavaClient).
    No firewalls between the two systems and the security files (C:\Document Settings\htran\.java.policy) are made up of the following 2 lines:
        grant codeBase "file:/home/jones/src/" {
            permission java.security.AllPermission;
        };Another issue that I am having is that the server process below is that it keeps on dropping off after a minute or two:
    C:\Documents and Settings\htran\JavaRMI\build\classes>java -Djava.rmi.se
    rver.codebase='http://clienthostname/LearningJavaClient/' -Djava.security.policy="C:\
    Documents and Settings\htran\.java.policy" -cp . LearningJavaClient.MyClient serverhostname
    This exercise has worked fine when running all the codes on the same host.
    I am running Netbeans 5.5, JDK1.5.0_11 on Windows 2000 (Server) & XP (Client).
    Any assistance would be appreciated.
    Many thanks,
    Henry

    Hi Esmond,
    You still have an empty catch block for the IOException. Fix that first. I >can't possibly tell what's going on until you can at least bind the >service.OK. MyServer.java below no longer throws RemoteExceptions in both of its methods and added the print stacktrace to catch the empty IOException earlier.
    public class MyServer extends java.rmi.server.UnicastRemoteObject
        implements RemoteServer {
        public MyServer(  ) throws RemoteException { }
        public Date getDate(  ) {
            return new Date(  );
        public Object execute( WorkRequest work ) {
            return work.execute(  );
        public static void main(String args[]) {
            System.setSecurityManager(new RMISecurityManager());
            try {
                RemoteServer server = new MyServer(  );
                Naming.rebind("NiftyServer", server);
            } catch (java.io.IOException e) {
                // problem registering server
               System.out.println("IOexception from MyServer");
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println("General Exception from MyServer");
                e.printStackTrace();
    }The following error messages were produced when launching MyServer.class. I have broken it into 2 separate attempts. One with Dynamic Class Downloading & one without.
    Use CodeBase when launches MyServer.
    C:\Documents and Settings\abc\JavaRMI\build\classes>java -Djava.rmi.server.codebase='http://clienthostname/LearningJava/' -Djava.security.policy="C:\Documents and
    Settings\abc\.java.policy" -cp . LearningJava.MyServer
    IOexception from MyServer
    java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.net.MalformedURLException: no protocol: 'http://clienthostname/LearningJava/'
    at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
    at sun.rmi.server.UnicastRef.invoke(Unknown Source)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Unknown Source)
    at LearningJava.MyServer.main(MyServer.java:28)
    Caused by: java.net.MalformedURLException: no protocol: 'http://clienthostname/LearningJava/'
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at sun.rmi.server.LoaderHandler.pathToURLs(Unknown Source)
    at sun.rmi.server.LoaderHandler.getDefaultCodebaseURLs(Unknown Source)
    at sun.rmi.server.LoaderHandler.loadClass(Unknown Source)
    at java.rmi.server.RMIClassLoader$2.loadClass(Unknown Source)
    at java.rmi.server.RMIClassLoader.loadClass(Unknown Source)
    at sun.rmi.server.MarshalInputStream.resolveClass(Unknown Source)
    at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
    at java.io.ObjectInputStream.readClassDesc(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    ... 5 more
    Does NOT use CodeBase when launches MyServer
    C:\Documents and Settings\abc\JavaRMI\build\classes>java -Djava.security.policy="C:\Documents and Settings\abc\.java.policy" -cp . LearningJava.MyServer
    IOexception from MyServer
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: LearningJava.RemoteServer
    at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:385)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240)
    at sun.rmi.transport.Transport$1.run(Transport.java:153)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:149)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
    at java.lang.Thread.run(Thread.java:595)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
    at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
    at sun.rmi.server.UnicastRef.invoke(Unknown Source)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Unknown Source)
    at LearningJava.MyServer.main(MyServer.java:28)
    Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: LearningJava.RemoteServer
    at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
    at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:375
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240)
    at sun.rmi.transport.Transport$1.run(Transport.java:153)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:149)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
    at java.lang.Thread.run(Thread.java:595)
    Caused by: java.lang.ClassNotFoundException: LearningJava.RemoteServer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    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:242)
    at sun.rmi.server.LoaderHandler.loadProxyInterfaces(LoaderHandler.java:707)
    at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:651)
    at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:588)
    at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:628)
    at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294
    at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:238)
    at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1500)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1463)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
    ... 9 more
    I now understand that you do want to use dynamic class loading, and >moreover that you want to do it from the client to the server, in which >case you do need java.rmi.server.codebase at the client and you do >also need a codebase server. However the client and server can both >use the same codebase server, and indeed in this situation I don't >see why the server needs a codebase server or setting at all actually. I >don't really see why you want to use it from the client either, if this is a >closed system but that's your problem not mine.I now use only one codebase server. ie the one on the Client side where MyCalculation.class resides. You are right it is not necessary to use codebase when launching MyServer since the Client side does not need to download any additional classes over to the client side. Nevertheless, neither of the above startups (with/without) codebase worked even though the error messages were slightly different.
    Btw, can you explain what you mean by a "close system" compared to an "opened system"?
    java.net.MalformedURLException: no >protocol: 'http://clienthostname/LearningJava/'
    That doesn't make sense. Are you sure you're transcribing it correctly? >Also what line of code is throwing it?Here is the code for MyClient which explains that the line java.net.MalformedURLException: came from line 32, the printStackTrace() from IOException.
    public class MyClient {
        public static void main(String [] args)
          throws RemoteException {
          System.setSecurityManager(new RMISecurityManager());
            new MyClient( args[0] );
        public MyClient(String host) {
            try {
                RemoteServer server = (RemoteServer)
                    Naming.lookup("rmi://"+host+"/NiftyServer");
                System.out.println( server.getDate(  ) );
                System.out.println(
                server.execute( new MyCalculation(2) ) );    // line 28
            } catch (java.io.IOException e) {
                  // I/O Error or bad URL
                  System.out.println("IOException from MyClient");
               e.printStackTrace();
            }  catch (NotBoundException e) {
                  // NiftyServer isn't registered
                  System.out.println("NotBoundException from MyClient");
               e.printStackTrace();
            } catch (Exception e) {
                  System.out.println("General Exception from MyClient");
                  e.printStackTrace();
    }I wouldn't pay much attention to this message since the MyServer has difficulty registering itself to RMI registry. As a result, MyClient could not
    locate MyServer via RemoteServer interface before giving up altogether.
    Unfortunately, I have not being able to create an interface (e.g. >MyCalculation.class as an interface, MyCalculationImpl.class as the >actual implementation of MyCalculation) since WorkRequest is an >abstract class, which does not allow MyClient to instanciates >MyCalculation on line 28.
    I don't see why not. What error messages/exceptions are you getting?
    Are you referring to the execute() method on line 13 in >RemoteServer.classNo, I am referring to line 28 of MyClient.class above after the following failed attempts to create an interface for MyCalculation.java:
    public interface MyCalculation extends WorkRequest { // Got a syntax error: interface expected here in Netbeans.
    } Or
    public interface MyCalculation {}
    public class MyCalculation extends WorkRequest extends MyCalculation { ... # Obviously cannot extend more than one class.Any suggestion?
    No. I said the remote method implementation (i.e. in your xxxImpl >class) doesn't need to be declared to throw RemoteException. The >remote method definition in the remote interface certainly does. I have taken out the RemoteException from 2 methods in MyServer.java. ie implementation of the RemoteServer.java.
    In short, I have used only one codebase server but puzzled whether MyCalculation.class (have split it up into interface & implementation) will be passed over to the
    server side by referenced, value or Dynamic Class Downloading. I do not want it to use Dynamic Class Downloading to do this.
    Thanks,
    Henry

  • Dynamic class loading problem using unknown JAR archive and directory names

    I read the following article, which enlightened me a lot:
    Ted Neward: Understanding Class.forName().
    However, it took me some while to understand that my problem is the other way around:
    I know the name of the class, I know the name of the method,
    but my program/JVM does not know where to load the classes from.
    Shortly, my problem is that the server engine that I am writing
    uses two different versions of the same library.
    So I am trying out the following solution:
    My program is named TestClassPathMain.java
    Assume the two libraries are named JAR1.jar and JAR2.jar
    and the class/instance method that should
    be exposed to TestClassPathMain.java by them is named
    TestClass1.testMethod().
    As long as I was depending on just one library,
    I put JAR1.jar in the classpath before starting java,
    and I was happy for a while.
    At the moment I got the need to use another version of
    TestClass1.testMethod() packaged in JAR2.jar,
    a call would always access JAR1.jar's
    TestClass1.testMethod().
    I then decided to remove JAR1.jar from the classpath,
    and programmatically define two separate ClassLoaders, one for use
    with JAR1.jar and the other for use with JAR2.jar.
    However, the problem is only partly solved.
    Please refer to the enclosed code for details.
    (The code in the JAR1.jar/JAR2.jar is extremely simple,
    it just tells (by hardcoding) the name of the jar it is packaged in
    and instantiates another class packaged in the same jar using
    the "new" operator and calls a method on it. I don't enclose it.)
    The TestClassPathMain.java/UC1.java/UC2.java code suite was
    successfully compiled with an arbitrary of JAR1 or JAR2 in the classpath,
    however removed from the classpath at runtime.
    (I know that this could have been done (more elegantly...?) by producing an Interface,
    but I think the main problem principle is still untouched by this potential lack of elegancy(?))
    1) This problem should not be unknown to you experts out there,
    how is it generally and/or most elegantly solved?
    The "*** UC2: Variant 2" is the solution I would like best, had it only worked.
    2) And why arent "*** UC2: Variant 2" and
    "*** static UC2: Variant 2" working,
    while "*** Main: Variant 2" is?
    3) And a mal-apropos:
    Why can't I catch the NoClassDefFoundError?
    The output:
    *** Main: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** Main: Variant 2 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 2 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** UC1: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** UC1: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** static UC2: Variant 2 JAR 1 ***:
    Exception in thread "main" java.lang.NoClassDefFoundError: TestClass1
            at UC2.runFromJarVariant2_static(UC2.java:56)
            at TestClassPathMain.main(TestClassPathMain.java:52)
    TestClassPathMain.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class TestClassPathMain {
        public static void main(final String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
                // Commented out because I cannot catch the NoClassDefFoundError.
                // Why?
                try {
                    final TestClass1 testClass1 = new TestClass1();
                    System.out.println(
                        "\nThe class TestClass1 is of some unexplicable reason available." +
                        "\nFor the purpose of the test, it shouldn't have been!" +
                        "\nExiting");
                    System.exit(1);
                } catch (NoClassDefFoundError e) {
                    System.out.println("\nPositively confirmed that the class TestClass1 is not available:\n" + e);
                    System.out.println("\n\nREADY FOR THE TEST: ...");
                // Works fine
                System.out.println("\n*** Main: Variant 1 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 1 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                System.out.println("\n*** Main: Variant 2 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 2 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                final UC1 uc1 = new UC1();
                System.out.println("\n*** UC1: Variant 1 JAR 1 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC1: Variant 1 JAR 2 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                System.out.println("\n*** static UC2: Variant 2 JAR 1 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** static UC2: Variant 2 JAR 2 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                final UC2 uc2 = new UC2();
                System.out.println("\n*** UC2: Variant 2 JAR 1 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC2: Variant 2 JAR 2 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
        private static void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
        private static void runFromJarVariant2(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    UC1.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC1 {
        public void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
    UC2.java
    import java.lang.reflect.InvocationTargetException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC2 {
        public void runFromJarVariant2(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
         * Identic to the "runFromJarVariant2" method,
         * except that it is static
        public static void runFromJarVariant2_static(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    }

    2. i need to load the class to the same JVM (i.e. to
    the same environment) of the current running
    aplication, so that when the loaded class is run, it
    would be able to invoke methods on it!!!
    ClassLoader(s) do this. Try the URLClassLoader.
    (I was talking about relatively esoteric "security"
    issues when I mentioned the stuff about Class objects
    "scope".) You might use the URLClassLoader kind of
    like this.
    Pseudo-code follows:
    // setup the class loader
    URL[] urls = new URL[1];
    urls[0] = new URL("/path/to/dynamic/classes");
    URLClassLoader ucl = new URLClassLoader(urls);
    // load a class & use make an object with the default constructor
    Object tmp = ucl.loadClass("dynamic.class.name").newInstance();
    // Cast the object to a know interface so that you can use it.
    // This may be used to further determine which interface to cast
    // the class to. Or it may simply be the interface to which all
    // dynamic classes have to conform in your program.
    InterfaceImplementedByDynamicClass loadedObj =
        (InterfaceImplementedByDynamicClass)tmp;It's really not as hard as it sounds, just write a little test of
    this and you will see how it works.

  • Oracle Arrays and getVendorConnection API and Class Cast Exception

    I 've gone through various threads relating to the topic of Oracle Arrays and the getVendorConnecton API call to avoid the class Cast Exception.. i ve used all these but am still facing the problem...
    I would appreciate it if some one could resolve the following queries :
    I am using Weblogic 8.1 SP5 with oracle 8i
    1. I read that the need to use the getVendorConnection API to make pl/sql proc calls with oracle arrays from the WL Server wont be required to avoid classCastException...
    I tried to use the connection from the WL connection pool ..but it didnot work....I used the getVendorConnection API ..which also doesnot seem to work..
    I got the Heurisitc Hazard exception...I used the Oracle 9i driver ie ojdbc14.jar ...after this the exception is not coming but still the code doesnt seem to work...
    the snippet of the code is pasted below :
    ~~~~~~~~~~~~~~~~~~~~~~~code is : ~~~~~~~~~~~~~~~~~~~
    /*below :
    logicalCon is the Connection from the WL connection pool
    JDBCcon is the JDBC connection. */
    <div> try </div>
    <div>{ </div>
    <div>
    <b>vendorConn</b> = ((WLConnection)logicalCon).getVendorConnection();
    </div>
    <div>
    //Calling the procedure
    </div>
    <div>
    //java.util.Map childMap1 = JDBCcon.getTypeMap();
    </div>
    <div>
    java.util.Map childMap1 = <b>vendorConn</b>.getTypeMap();
    </div>
    <div>
    childMap1.put("SST_ROUTE_ENTRY", Class.forName("svm.stport.ejb.StaticRouteEntry"));
    </div>
    <div>
    //JDBCcon.setTypeMap(childMap1);
    <b>vendorConn</b>.setTypeMap(childMap1);
    </div>
    <div>
    // Create an oracle.sql.ARRAY object to hold the values
    </div>
    <div>
    /*oracle.sql.ArrayDescriptor arrayDesc1 = oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", JDBCcon); */
    </div>
    <div>
    oracle.sql.ArrayDescriptor arrayDesc1 =
    oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", <b>vendorConn</b>); // here if i use the JDBCcon it works perfectly.... <u>^%^%^%</u>
    </div>
    <div>
    code to fill in the sst route entry array....
    .....arrayValues1 */
    </div>
    <div>
    /* oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, JDBCcon, arrayValues1); */
    </div>
    <div>
    oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, <b>vendorConn</b>, arrayValues1);
    </div>
    <div>
    callStatement = logicalCon.prepareCall( "? = call procName(?, ?, ?)");
    </div>
    <div>
    /* ..code to set the ?s ie array1 */
    </div>
    <div>
    callStatement.execute();
    </div>
    <div>
    }catch(Exceptio e){
    </div>
    <div>
    }</div>
    <div>
    finally </div>
    </div>{</div>
    <div>System.out.println(" I ve come to finally"); </div>
    <div>}</div>
    <div>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~code snippet ends here ~~~~~~~~~~~~~~``
    </div>
    I have observed that the control immediately comes to the finally block after the call to the createDescriptor line above with <u>^%^%^%</u> in the comment. If i use the JDBCCon in this line...it works perfectly fine.
    Any pointers to where anything is getting wrong.
    I have jst set the vendorCon to null in the end of the file and not closed it. Subsequently i have closed the logicalCon. This has been mentioned in some of the thread in this forum also.
    Thanks,
    -jw

    Jatinder Wadhwa wrote:
    I 've gone through various threads relating to the topic of Oracle Arrays and the getVendorConnecton API call to avoid the class Cast Exception.. i ve used all these but am still facing the problem...
    I would appreciate it if some one could resolve the following queries :
    I am using Weblogic 8.1 SP5 with oracle 8i
    1. I read that the need to use the getVendorConnection API to make pl/sql proc calls with oracle arrays from the WL Server wont be required to avoid classCastException...
    I tried to use the connection from the WL connection pool ..but it didnot work....I used the getVendorConnection API ..which also doesnot seem to work..
    I got the Heurisitc Hazard exception...I used the Oracle 9i driver ie ojdbc14.jar ...after this the exception is not coming but still the code doesnt seem to work...
    the snippet of the code is pasted below :
    ~~~~~~~~~~~~~~~~~~~~~~~code is : ~~~~~~~~~~~~~~~~~~~Hi. Show me the whole exception and stacktrace if you do:
    try
    vendorConn = ((WLConnection)logicalCon).getVendorConnection();
    java.util.Map childMap1 = vendorConn.getTypeMap();
    childMap1.put("SST_ROUTE_ENTRY" Class.forName("svm.stport.ejb.StaticRouteEntry"));
    vendorConn.setTypeMap(childMap1);
    oracle.sql.ArrayDescriptor arrayDesc1 =
    oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR",
    vendorConn);
    oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, vendorConn, arrayValues1);
    callStatement = logicalCon.prepareCall( "? = call procName(? ? ?)");
    callStatement.execute();
    }catch(Exception e){
    e.printStackTrace();
    finally
    try{logicalCon.close();}catch(Exception ignore){}
    System.out.println(" I ve come to finally");
    /*below :
    logicalCon is the Connection from the WL connection pool
    JDBCcon is the JDBC connection. */
    <div> try </div>
    <div>{ </div>
    <div>
    <b>vendorConn</b> = ((WLConnection)logicalCon).getVendorConnection();
    </div>
    <div>
    //Calling the procedure
    </div>
    <div>
    //java.util.Map childMap1 = JDBCcon.getTypeMap();
    </div>
    <div>
    java.util.Map childMap1 = <b>vendorConn</b>.getTypeMap();
    </div>
    <div>
    childMap1.put("SST_ROUTE_ENTRY", Class.forName("svm.stport.ejb.StaticRouteEntry"));
    </div>
    <div>
    //JDBCcon.setTypeMap(childMap1);
    <b>vendorConn</b>.setTypeMap(childMap1);
    </div>
    <div>
    // Create an oracle.sql.ARRAY object to hold the values
    </div>
    <div>
    /*oracle.sql.ArrayDescriptor arrayDesc1 = oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", JDBCcon); */
    </div>
    <div>
    oracle.sql.ArrayDescriptor arrayDesc1 =
    oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", <b>vendorConn</b>); // here if i use the JDBCcon it works perfectly.... <u>^%^%^%</u>
    </div>
    <div>
    code to fill in the sst route entry array....
    .....arrayValues1 */
    </div>
    <div>
    /* oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, JDBCcon, arrayValues1); */
    </div>
    <div>
    oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, <b>vendorConn</b>, arrayValues1);
    </div>
    <div>
    callStatement = logicalCon.prepareCall( "? = call procName(?, ?, ?)");
    </div>
    <div>
    /* ..code to set the ?s ie array1 */
    </div>
    <div>
    callStatement.execute();
    </div>
    <div>
    }catch(Exceptio e){
    </div>
    <div>
    }</div>
    <div>
    finally </div>
    </div>{</div>
    <div>System.out.println(" I ve come to finally"); </div>
    <div>}</div>
    <div>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~code snippet ends here ~~~~~~~~~~~~~~``
    </div>
    I have observed that the control immediately comes to the finally block after the call to the createDescriptor line above with <u>^%^%^%</u> in the comment. If i use the JDBCCon in this line...it works perfectly fine.
    Any pointers to where anything is getting wrong.
    I have jst set the vendorCon to null in the end of the file and not closed it. Subsequently i have closed the logicalCon. This has been mentioned in some of the thread in this forum also.
    Thanks,
    -jw

Maybe you are looking for

  • IMac DVD player no longer working

    Hi, I have Mac OS X version 10.6.8 My iMac is not playing DVDs anymore. When I insert a DVD a pop-up window appears saying: "You inserted a blank DVD. Choose an action from the pop-up menu or click ignore." The DVD I inserted isn't blank and it says

  • 用虚拟立方体显示数据源数据报错001 Error in BW & 001 Invalid parameter.

    事情是这样的: 1. 我用RSO2建立一个数据源,table选的是"SFLIGHT" 2. 提取页面我也选了u201C同步提取SAPI(用于虚拟块和测试)u201D 3. 建立虚拟立方体,然后转换,然后仅激活DTP. 但是我选u201C显示数据u201D时,就报这样的错: 001 Error in BW. 001 Invalid parameter. 我确定数据源没问题,因为可以读取预览数据.我在cmod里写过ABAP代码,不过后来删了. 求解 Edited by: peteron on Sep

  • Using 5th generation IPOD on two computers

    I just bought a new 30GB 5th generation Ipod. I travel for the government - one laptop I use at home, the other I use when traveling overseas. I use the same IPOD on both computers - or so I thought. Now I discover that when I try to use the same IPO

  • Exchange 2003

    I have one problem. At work we are using exchange 2003 and I'd like to read and asnwer my email at home using mail.app, but I cannot. How I set mail.app? I have to use exchang or exchange IMAP? I can read my mail wit my Iphone, I use the same usernam

  • The Warm Phone Issue (jut my 2 pennies)

    My question is; what exactly in installed in the space just below the ear speaker behind the screen? Which is the only area that gets noticeably (and for a new owner) worryingly warm. Is it the battery, memory, GPS antenna? While I understand the any