Dynamic class type casting?

Anyone know how to synthesize changing the type of a class after the instance is created?
I have a base class that has a number of sub classes. When instances are created, I cannot create subclass instances because the required information is not available. However, after the instances are created, I can determine the subclass I would like the instance to be.
The subclasses don't have any new fields, they just override base class methods. The subclass I want is determined by a field in the base class that is not known at base class creation time. It is set at a later point.
Any ideas?
I could delay object creation until I know exactly which sub classs I want, but that would increase code size considerably. I would like a neat mutation mechanism or something similar so I could change the type of the class.
I could also recreate the object when I know the subclass I want, but that seems expensive.

I have a base class that has a number of sub classes.
When instances are created, I cannot create subclass
instances because the required information is not
available. However, after the instances are created, I
can determine the subclass I would like the instance
to be.You might consider the prototype pattern. In the prototype pattern, you have a prototype manager and prototype objects it manages. You register prototypes with the prototype manager using a key (think of a key abstractly here) and retrieve the prototypes using the same key. When you retrieve a prototype from the prototype manager you clone the prototype, which is much faster than instantiating an object, and then you use the clone.
From what you said above it seems that you have all of the right elements for application of the pattern. You said you have a base class with many sub-classes and that you know which sub-class you want when you have specific information.
>
The subclasses don't have any new fields, they just
override base class methods. The subclass I want is
determined by a field in the base class that is not
known at base class creation time. It is set at a
later point.
In implementing the pattern it would be a good idea to create a new class that manages the information you require (as previosuly determined by the field in the base class) to create a subclass, removing it (the field) from the base class completely. This new class is used as your key to retrieve prototypes from the prototype manager.public class OldBaseNowIsKey {
   String field;
   public String getField() { return field; }
   public void setField(String s) { field = s; }
public class NewBaseClass {
   public void doSomethingPolymorphic() { }
public class PrototypeOne extends NewBaseClass {
   public void doSomethingPolymorphic() { }
public class PrototypeManager {
   private Hashmap prototypes;
   static {
      // This is one way to register prototypes and not
      // necessarily the best.
      prototypes = new Hashmap();
      prototypes.put("prototypeOneKey", new PrototypeOne());
   public static NewBaseClass get(OldBaseNowIsKey key) {
      return (NewBaseClass) prototypes(key.getField());
public class ClassThatUsesPrototype {
   public void someMethod() {
      // Something happens and we know the value of the
      // field in the old base class but now we use that
      // information to create a key or reuse an existing
      // key object.
      OldBaseNowIsKey key = new OldBaseNowIsKey();
      key.setField(theInformation);
      // Now we know have the necessary information to
      // create a sub-class only we will be cloning which
      // is faster.
      NewBaseClass prototype = PrototypeManager.get(key).clone();
      prototype.doSomethingPolymorphic();
I could delay object creation until I know exactly
which sub classs I want, but that would increase code
size considerably. I would like a neat mutation
mechanism or something similar so I could change the
type of the class.Sounds like C++.

Similar Messages

  • Dynamic [Runtime] type casting in Java

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which returns some object
    /*<b>I need to typecast above object with the class name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast the object with class whose name is passed as the method parameter?

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which
    returns some object
    /*<b>I need to typecast above object with the class
    name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast
    the object with class whose name is passed as the
    method parameter?Perhaps a little more background on the project (what you are trying to do) will help the experts here answer?
    /*with a class that takes a noarg constructor*/
    public Object getObject(String classname) throws Exception
      //might want to get a bit more specific with which exceptions it will throw
      return Class.forName(classname).newInstance();
    }Do I think this sometimes is indicative (perhaps even more often than not), of a possible design flaw? Yes..
    It gets a little trickier if you have constructors (you have to create a Class object representing the string with the .forName(..) ..and then use some reflection to determine constructors and then a bit of logic to determine which of those to use...)
    ~Dave

  • Dynamic Type casting

    Can we dynamically type-cast an object reference passed to Object Clss to that specific class?
    Here is what I want to do.
    I am going to pass an object reference to a method, which has Object class as parameter to it, as shown below. Using getClass() or some other way, I want to dynamically typecast this reference to the original Class and call some method of this Class.
    void test (Object ref1){
    ((ref1.getClass())ref1).writeLog();
    By doing this, am I violating the basic Object Orineted rules?

    I mean, consider an hypothetical case (which is wrong
    from OO point of view) that there are suppose 10
    classes in my system. None of them related to each
    other, all are independent classes. But each one has a
    method called, writeLog(). Now I want to write one
    method which will be called by each of these classes
    (in some 11th class), which will have "Object" as a
    parameter. Now using the actual reference I want to
    call the corresponding writeLog() method.
    1 - Point out to management that the design is now officially broken.
    2 - Point out that if the design is not fixed then any solution that impliments the changes will cost more to maintain in the future and will likely lead to instabilities in the system (due to complexity.)
    3 - Implement one of the suggested solutions and make sure that you put in a lot of error checking and logging in the hacked solution.
    4 - Produce extensive documentation about the impact of changing any of the objects that you are relying on. Push it to anyone and everyone that might ever touch or even suggest changes to the code.
    Doing all of the above allows you to live stress free when the next revision breaks because someone didn't understand the implications of your hacked solution. You will be able to find the problem quickly and point out that it had nothing to do with your code but rather because someone else did not follow the complete documentation that you produced. And then when they complain that your solution was a hack you can point out that you explained that previously as well.

  • Type Casting to a Class

    I'm getting an instance of a class through the newInstance() method.I want to access that class members through this newly created object.But to do this, I have to typecast the object by its class name.In my case, the class is a dynamic one(i.e., unknown at the time of creating that object).I get the class name as a string through the getName() method.
    HOW CAN I DO THE TYPE CASTING OR IS THERE ANY OTHER METHOD TO SOLVE THIS TYPE OF PROBLEM.
    Example :
    In this example, i have created an object t2 in the same class.but,in actual case, that object is created in some other program called test2. And test2 doesnt know abt the class(test1) being used.And is being determined at runtime (i.e., dynamical).
    class test1
         int i = 10;
         String s;
         public static void main(String a[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException
              test1 t = new test1();
              System.out.println("I = " + t.i);
              System.out.println("Class Name = " + t.getClass().getName());
              t.s = t.getClass().getName();
              Object t2 = t.getClass().newInstance();
              System.out.println("t2 I = " + ((test1)t2).i);
              System.out.println("t2 Class Name = " + t2.getClass().getName());

    If you have no idea what members the class could have in compile time, then how can you set them in runtime?
    I think you should give another though to your OO design...

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

  • Can we type cast class into interface?

    Hello all,
    Can we type cast class into interface?
    If it can ,pls explain me in which suituation can we do?

    You don't need to explicitly typecast a class to an interface, if the class is implementing the interface.
    Example: List list = new ArrayList();    // Cast not required.And search on Google first. I'm sure this question would be answered by the lamest of tutorials.

  • Type Casting Exception

    I have an attribute CategoryId in my VO of type oracle.jbo.domain.Number. I am trying to use the expression of Boolean item in JHS as #{row.CategoryId != 4}
    Here is the generated JSF code:
                          <af:column id="s141NewItem3Col" noWrap="true" width="100"
                                     rowHeader="false">
                            <f:facet name="header">
                              <af:outputLabel value="CAtIDDeq4" showRequired="false"
                                              id="ol18"/>
                            </f:facet>
                            <af:inputText id="s141NewItem3"
                                          value="#{row.CategoryId != 4}"
                                          label="CAtIDDeq4" required="false"
                                          readOnly="#{((pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn']))) or ((!pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn'])))}"></af:inputText>
                          </af:column>I am getting the run time exception as "Can not convert 4 of type class oracle.jbo.domain.Number to class java.lang.Long"
    I am wondering how the row.CategoryId is treated as Long?. PLease advise. Also, will I be able to use type casting expressions in J Headstart/JSF Expression Language?
    Thanks, Pradeep

    I am trying to set disabled property of an item SubCategory dynamically based on CategoryId value. I guess the transient attribute will not work for newly created records as the transient attribute will be null for newly created records before save is performed. However, the expression #{row.bindings.CategoryId.attributeValue.value== 4 ? false : true} is working fine. row.bindings.CategoryId.attributeValue seem to be returning Long and, row.bindings.CategoryId.attributeValue.value might be returning a Number.

  • Type casting in OOPS ABAP

    Hi Team,
                 Could any one explain me about Type casting used in oops abap and in what circumstances it is
    used with an example.
    Regards,
    Pradeep P.

    Hi,
    Hi,
    Go to ABAPDOCU tcode and see example programs in abap objects section, you will find separate programs for upcasting and downcasting .
    Up-Cast (Widening Cast)
    Variables of the type reference to superclass can also refer to subclass instances at runtime.
    If you assign a subclass reference to a superclass reference, this ensures that
    all components that can be accessed syntactically after the cast assignment are
    actually available in the instance. The subclass always contains at least the same
    components as the superclass. After all, the name and the signature of redefined
    methods are identical.
    The user can therefore address the subclass instance in the same way as the
    superclass instance. However, he/she is restricted to using only the inherited
    components.
    In this example, after the assignment, the methods GET_MAKE, GET_COUNT,
    DISPLAY_ATTRIBUTES, SET_ATTRIBUTES and ESTIMATE_FUEL of the
    instance LCL_TRUCK can only be accessed using the reference R_VEHICLE.
    If there are any restrictions regarding visibility, they are left unchanged. It is not
    possible to access the specific components from the class LCL_TRUCK of the
    instance (GET_CARGO in the above example) using the reference R_VEHICLE.
    The view is thus usually narrowed (or at least unchanged). That is why we
    describe this type of assignment of reference variables as up-cast. There is a
    switch from a view of several components to a view of a few components. As
    the target variable can accept more dynamic types in comparison to the source
    variable, this assignment is also called Widening Cast
    Static and Dynamic Types of References
    A reference variable always has two types at runtime: static and dynamic.
    In the example, LCL_VEHICLE is the static type of the variable R_VEHICLE.
    Depending on the cast assignment, the dynamic type is either LCL_BUS or
    LCL_TRUCK. In the ABAP Debugger, the dynamic type is specified in the form
    of the following object display.
    Down-cast (Narrowing Cast)
    Variables of the type “reference to superclass” can also refer to subclass instances
    at runtime. You may now want to copy such a reference (back) to a suitable
    variable of the type “reference to subclass”.
    If you want to assign a superclass reference to a subclass reference, you must
    use the down-cast assignment operator MOVE ... ?TO ... or its short form
    ?=. Otherwise, you would get a message stating that it is not certain that all
    components that can be accessed syntactically after the cast assignment are
    actually available in the instance. As a rule, the subclass class contains more
    components than the superclass.
    After assigning this type of reference (back) to a subclass reference to the
    implementing class, clients are no longer limited to inherited components: In the
    example given here, all components of the LCL_TRUCK instance can be accessed
    (again) after the assignment using the reference R_TRUCK2.
    The view is thus usually widened (or at least unchanged). That is why we describe
    this type of assignment of reference variables as down-cast. There is a switch
    from a view of a few components to a view of more components. As the target
    variable can accept less dynamic types after the assignment, this assignment is
    also called Narrowing Cast
    Reward if helpfull,
    Naresh.

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

  • 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

  • Type cast exception

    Hi Guys,
    I am pretty new at generics and have started reading all material available online. Shown below is the API that I am using
    package api;
    public interface CS<C extends MyConfig> extends S {
    package api;
    public interface MyConfig {
    package api;
    public interface MySession {     
         public <C extends MyConfig, T extends ResourceContainer<? extends C>>
         T createContainer(CS<C> aPredefinedConfig);
    package api;
    public interface NC extends ResourceContainer<NCC>  {
    package api;
    public interface NCC extends MyConfig {
    package api;
    import java.io.Serializable;
    public interface ResourceContainer <T extends MyConfig> extends Serializable {
    package api;
    public interface S {
         public abstract boolean equals(Object other);
         public abstract int hashCode();
         public abstract String toString();
    }And below is my implementation
    package impl;
    import api.NC;
    public class NCImpl implements NC {
    package impl;
    import api.CS;
    import api.MyConfig;
    import api.MySession;
    import api.ResourceContainer;
    public class MySessionImpl implements MySession {
         public <C extends MyConfig, T extends ResourceContainer<? extends C>> T createContainer(
                   CS<C> predefinedConfig) {
              NCImpl ncimpl = new NCImpl();
              return ncimpl; //Error Type mismatch: cannot convert from NCImpl to T
    }As shown above I get error at line 'return ncimpl' But NCImpl implements the NC which extends ResourceContainer<NCC> so shouldn't it be capable of Type casting to T or I am missing something.
    Thanks a lot for your response in advance

    continuation of stack trace .................
    [INFO] ------------------------------------------------------------------------
    [ERROR] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    [INFO] ------------------------------------------------------------------------
    [INFO] Trace
    org.apache.maven.BuildFailureException: Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:579)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:478)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:516)
    at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:114)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
    ... 16 more
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 5 seconds
    [INFO] Finished at: Thu Feb 12 10:39:43 IST 2009
    [INFO] Final Memory: 14M/81M
    [INFO] ------------------------------------------------------------------------
    [abhayani@localhost GenericsTest]$

  • Why we use type casting  ' ?='

    Hii Team
    sample code for fetching the input value from search view which is connected to btq1order contextnode
    DATA : lr_qs TYPE REF TO cl_crm_bol_dquery_service,
           lr_qr TYPE REF TO if_bol_bo_col,
    lr_qs ?= me->typed_context->btq1order->collection_wrapper->get_current( ).
    lr_qr = lr_qs->get_query_result( ).
    I am new to SAP CRM .while understanding the code i got stuck in one problem that ,
    1.what is the main purpose behind
    TYPE CASTING ie;  '?='
    2.what happens if we write ?=  becoz if we write  '='  instead of  '?='  the system thows an error.
    3.when to use this operator ?= and when we cannot use ?
    It is used almost every where in BOL coding .please help me  by giving complete explaination with an example if possible.
    Thanks in Advance

    Hi Abhishek,
    Please check returning parameter type for get_current_dquery() method. In case returning type is mutually convertible then you don't have to use type casting.
    But in case where you are taking results in some other type where results are compatible but with different structure then you use type casting.
    best example would be cl_crm_bol_entity and if_bol_bo_property_access. Here property access is an interface to class and hence we use type casting.
    Please refer to:
    type casting
    You can find more documentation on internet if you search for type casting.
    Regards,
    BJ

  • Type Casting? When to use this concept?

    There is one question bothering me very very much.
    When should I use type casting?
    For example
    ClassNameQ c = (ClassNameQ) ......displayable
    How do I know which 'cast type' to use? Is there a suitable pattern
    we need to follow so that we can know 'Ah this is the cast
    we need to use'
    Please can any one point out which 'Cast type' points needs to be
    followed?
    Regards

    You can Cast an object from any subclass to its superclass,
    or from a superclass to the sublass, if the object is already
    an object of the subclass.
    I have a class named Name:
    public class Name {
    I have a subclass named LastName:
    public class LastName extends Name { [/b]
    And another named FirstName:
    [b]public class FirstName extends Name { [/b]
    I create an object like this:
    [b]LastName ln = new LastName("Johnson");
    Then pass it to a method that can work on all names:
    capitalFirstLetter(ln);
    capitalFirstLetter(Name n) {
    Now n in CapitalFirstLetter can be used only as a Name
    object. Anything specific to the LastName object can't be used.
    So if I need to use things specific to LastName I have to cast
    the object to LastName. There is a problem, however, since this
    method can work on all Names, so I don't know if the Name is
    a LastName or not. The object itself DOES know, however, and
    we can test, so we would cast to a subclass as follows:
    if (n instanceof LastName) {
    LastName ln = (LastName)n;
    ln.addToGeneology();
    } else of (n instanceof FirstName) {
    FirstName fn = (FirstName)n;
    fn.addOccurance();
    Steve

  • Type casting or something of the sort

    This might sound stupid, but I have a 25 character something such as:
    1hjfu7y4$y*3fji2389561##k
    and I do not know what type it is. It is not a string though, and that is the problem. Is there any sort of equivalent in AS to type casting of c++? Some sort of way to dynamically make this into a string?

    typeof():
    trace(typeof(1hjfu7y4$y*3fji2389561##k));

  • Type casting for properties accessed in COM Object

    I have a com object that I need to access which provides my a
    list of addresses in an Array. The object give me a property that
    has a count for the number of addresses and then I have a loop that
    calls the property which contains the address details to get each
    individual address each time passing to the property the INDEX
    value on the loop.
    This errors out each time.
    The error I get is
    Error casting an object of type to an incompatible type.
    This usually indicates a programming error in Java, although it
    could also mean you have tried to use a foreign object in a
    different way than it was designed.
    It appears the the variable type of the index is not
    compatible with the property of the component(which is an int).
    IS there some way to type cast the variable used as the index
    for CFLOOP to that of an INT?

    You can try to use the JavaCast("int", myValue) function. It
    works great for Java objects, but I'm not sure how well it will
    work for COM. Worth a try, I guess.
    In your case it would be something like:
    <cfobject type="COM" context="INPROC" action="create"
    name="MR" class="DLLNAME">
    <cfloop from="1" to="#AddressCount#" index="i">
    <cfset VDname = mr.vdsname(JavaCast("int", i))>
    <cfset VDaddress = mr.vdsaddress(JavaCast("int", i))#>
    <cfset VDXML = mr.VDSXML(JavaCast("int", i))>
    </cfloop>

Maybe you are looking for

  • Imports not available

    Hi I am trying to do an ADFBC Application. When i am writing a java classes, I observe that some of the imports are not available. Ex : JboException. If I write a java file in Model , then i am able to import JboException. But in the ViewController,

  • Internet slowed down to nill thanks to upgrade

    since i updated my old version macbook air the internet has gone from fast to snailspeed and i have no idea why.. any1 got any idea's to solve it or atleast make it bareable to live with

  • Boot Camp Wifi Not Working; Windows Vista 32 Bit

    Hey, alright, I got this huge problem. I installed Windows Vista 32-Bit edition on Boot Camp 2.0. I installed the drivers on my Leopard CD. For some reason I can connect to the net on the Leopard side (which I am using right now) and I just can't get

  • How do I transfer docs and pics from one ipad2 to my new iPad mini

    I got an iPad mini as a gift and want to transfer everything from my iPad 2 to the mini. How do I do this

  • Editing Between Libraries Notifications

    In working with 10.1.1. and the new Libraries, I find myself working with assets located in different libraries. Is there any possible way of disabling - turning off - the notification window that keeps popping up and reminding me that I'm editing be