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

Similar Messages

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

  • Interfaces casts are type-checked differently to class casts?

    hi,
    this is a multipost of
    http://forum.java.sun.com/thread.jspa?threadID=677488&tstart=0
    as i'm hoping some compiler guys are hanging around in here :)
    I'm just wondering why interfaces are type-checked differently to class casts when casting between siblings in the inheritance hierarchy.
    e.g. casting a String to an Integer fails, but declaring
    interface IString {
       String toUpperCase();
    interface IInteger {
       int intValue();
    } and casting between IString and IInteger works fine?
    any help appreciated,
    thanks,
    asjf

    Unless you have specific memory usage requirements so that you must use arrays, just use a java.util.List:
    public abstract class Type<A extends Arg> {
        protected abstract List<A> method();
       // or if the only needs to read it can be more convenient to have
        protected abstract List<? extends A> method2();
    public class Sub extends Type<SubArgs> {
        protected List<SubArgs> method() { ... }
        // sub class can be more specific for method2 if it wants to
        protected List<SubArgs> method2() { ... }
    }

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

  • Type casting problem in the JSP

    Hi,
    I am type casting an Object variable to a interface Variable. I am not getting any error if i have the same code in the servlet but i am getting ClassCast Exception if i have the same code in the Scriplets part of the JSP.
    The code is as follows
    String strKey = " SomeString";
    Context context = new InitialContext();
    java.lang.Object obj = null;
         obj = context.lookup(strKey);
         ContentBroker objCB = null;
         objCB = (ContentBroker)obj; // Error is happening here
    ContentBroker is an inteface.
    I have included the jar files of ContentBroker in the classpath.
    Can anyone please tell me how to eliminate this error.?
    thanks in advance,
    Saravanan

    In that case it's a classloader issue.
    Since the object is bound in the context, I assume that you have made the class available to your server, and you have the class in WEB-INF/classes or in a jar inside WEB-INF/lib.
    Since they're being loaded by two different classloaders, the classes are seen as different by the JVM, thus the ClassCastException.
    Try removing the class from the web-app and let us know what happens.
    BTW. Which servlet container are you using?

  • How to use Type Casting in JSF Expression Language

    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 JSF as #{row.CategoryId != 4}
    Here is the 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 JSF Expression Language?
    Thanks, Pradeep

    use attributeValue
    Try *#{row.bindings.CategoryId.attributeValue != 4}* ?
    Check this thread for details which discusses about the same:
    El expression to disable  or enable
    Thanks,
    Navaneeth

  • Type casting in JAX-RPC

    Hello
    I was trying to do a JAX-RPC application, and I had some problems with type casting. My application worked fine with primitive types, vectors of primitive types, and beans with primitive type properties. But it didn't work with vectors of beans, or ArrayList's of beans... It couldn't deserialize the result on client side... Can anyone help?
    The Java Web Services Tutorial says that JAX-RPC supports beans and vectors, but I had the impression that this is not a "recursive" support, like "beans with vectors" or "vectors of beans"... Does it make sense?
    By the way, I was using a DII client...
    Thanks,
    Alexandre Murakami

    Hello!
    Thanks for the reply! I can't put the code of my application here (because it's quite big and it's from work)... But I followed the dii client example from the Web Services Tutorial...
    I'm trying to do a kind of a general client... The parameters are the URL of the service, the name of the operation, a list of parameters and the return type class.. And it takes the rest of the service information from the WSDL file... About the return type, I take the QName of the return type from the WSDL:
    <message>
    <part name="result" type="...">...
    then I call the call.setReturnType(QName, Class) method. The return type was an array of a very simple bean, something like:
    class Person {
    String name;
    int age;
    public String getName() {...}
    public void setName(...) {...}
    public int getAge() {...}
    public void setAge(...) {...}
    I don't know if the information I put here is enough... but anyway, thanks for the reply!
    Alexandre Murakami

  • Type casting in Java

    Hi,
    Can we do explicit type casting vigorously in a java class? Im in a situation that i've to do explicit casting 40 to 50 times in a class. Is there any overhead for JVM or any performance issue with this?

    Why do you cast so often? It's sounds like a weird design. Casting is pretty cheap.
    Kaj

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

Maybe you are looking for

  • Return Order Changed/Re-assigned to Diff Sales Order

    Hi All SD gurus, I have a very weird case here and am wondering whether anyone can gives me some leads here. A return order ( customized ) was created with reference to a Sales Order. A subsequent return delivery and Post Goods Receipt was performed.

  • In need of help to find decent external home network drive !

    Hi, I am in need of an external home network drive in either 1 or 2TB form. It will be for an imac and macbook pro + ps3 to use. I saw this Western Digital one but was not sure how good it is - http://www.wdc.com/en/products/products.aspx?id=300 I wo

  • Film Look ...

    Hi, I have been racking my brains as to figure out how to give that 'film look' to PAL video in FCE. Using a clip, I 'selected all' and went into video effects to find de-interlace (or is 'interlace' that I need) ... I clicked on de-interlace and not

  • String replace

    String has a replace method for chars, something the likes of String replace(char a, char b) I tend to think it would be nice to ammend String further with String replace(String a, String b) proponents/opponents? It seems like a nice thing to have.

  • Changes

    If you could make any changes to the Java language, what would they be? What aspects of the language annoy you and how do you think they could be implemented in a better way? For instance I would make it so that you could call by reference as well as