Casting string to a class type

is it possible to typecast a string to a classtype?
Example:
if a string is stored in a vector v and xyz is a class then is the following statement correct :
((xyz)v.elementAt[2]) ??
if not then what should i do to typecast it?

Navy_Coder wrote:
jverd wrote:
Navy_Coder wrote:
streetfi8er wrote:
is it possible to typecast a string to a classtype?
Example:
if a string is stored in a vector v and xyz is a class then is the following statement correct :
((xyz)v.elementAt[2]) ??
if not then what should i do to typecast it?Do you understand what typecasting is? What you're asking could be compared to taking your truck to a mechanic and asking if they can just turn it into a banana. You can't cast one object to another completely unrelated object.In fact, you can't cast objects at all.On second thought ......
enum Destination {
ETERNAL_DAMNATION, PITS_OF_HELL, OCEAN, VAT_OF_ACID;
ObjectManager.cast(myInstance, Destination.PITS_OF_HELLO);
ObjectManager.cast(calebsBrain, Destination.VAT_OF_ACID);
IMHO, this is still casting a reference, not an object.

Similar Messages

  • Is it possible to pass a string representing a class name in java as an arg

    Hi, this is probably a bit of a stupid question, but one that has me quite confused all the same!
    Is it possible to pass a string or class name etc. representing a type of class in java, to a method so that instead of having to redefine a method with say the following args:
    public SolarPanels[] bestPVPanels(int budget, int percent) {
            HashMap<Integer, SolarPanels> panelsMap    = new HashMap<Integer, SolarPanels>();
    }As at present needing to create a methods bestWindTurbine() and many others exactly the same, but for the type, I would instead like to be able to create a method like:
    public Object[] bestRenewable(int budget, int percent, String aClassName) {
            HashMap<Integer, aClassName > renewableMap    = new HashMap<Integer, aClassName >();
    }But cant sus how to do this as passing a String is off course going to cause problems unless its it possible to cast a string to a class name, any help or advance would be much appreciated.
    Thanks in advance
    Pat Nevin

    pNev wrote:
    But cant sus how to do this as passing a String is off course going to cause problems unless its it possible to cast a string to a class nameIt's not. You can do things like
    Class.forName(classNameInString);But that will only return a Class object.
    And as Java generics are erased at runtime, passing the class name to the method is useless as it is too late to use it anyways.
    Ah, Peter's way is what I was thinking of. Too early in the morning.
    Edited by: Kayaman on 23.6.2010 10:02

  • Coercing string to MovieClip class

    I've been learning coercion between String and Number and
    simple stuff, but now I have a class that the books don't cover.
    This is best explained by example (this isn't the end goal, just a
    learning example).
    On the stage in frame 1, I have a MovieClip instance named
    shape_mc.

    In your first post you create a variable fubar with no
    particular type and then make it a String by concatenating two
    other variables. Next you attempt to cast String to MovieClip -
    this is what is wrong with the code. Casting works only if an
    object somehow is related to other object - in this instance if
    fubar data type was related somehow to MovieClip (by extension for
    example).
    In order to use a string to point to an object - you need to
    use an associative array syntax:
    parentObject["string"] - given that an object "string" is in
    the scope of parentObject.
    The following syntax will work (if the movieclip is in the
    scope of "this"):
    var pre:String="shape";
    var suf:String="_mc";
    var fubar:* = MovieClip(this[pre + suf]);
    Again, the key is to use a correct scope.
    As for the flv files, there is no need to cast at all. FLVs
    are not MovieClips. It is not clear how you want to play FLVs. Are
    they on the server? If so - you need the url to them only (which
    are strings). If they are progressive (downloaded via http) your
    code may look something like:
    var flvURL:String;
    function clickListener(e:MouseEvent):void{
    flvURL = e.target.name.toString().split("_")[0] + "_flv";
    //some time later:
    netStream.play(flvURL);
    Of course this is just a concept - real code should be
    different.

  • Determine class type of Generic Parameter (not via getGenericSuperclass()!)

    I need to know the class type of a generic Parameter. Please imagine this class:
    class MyGenericClass<T>
    }In cases where other classes derived from MyClass and defined the generic parameter (like MyDerivedClass extends MyGenericClass<String>),
    this snippets works just fine:
    (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];But now I have no inheritance but the definition of the type parameter via instantiation:
    MyGenericClass<String> entity = new MyGenericClass<String>();The method "getGenericSuperclass()" does not suit my needs because it does not target the actual class. Nor can "getTypeParameters() " help me...
    After countless trying to retrieved the type information, I still have no clue how to determine for that case that (in my example) the type parameter
    is a 'String'.
    Does anyone know the solution?

    Serethos_0 wrote:
    Sure I could pass the class type itself as parameter to be stored in 'exportClassType'. But I only tried to adapt the idea used e.g. in Generic DAOs
    as descibed here: [http://community.jboss.org/wiki/GenericDataAccessObjects]. The big difference is, that in the Generic DAO example the typed
    information is available within the class definition ..
    Besides that I am open for any other suggestion!I would recommend passing around the Class object as you say.
    Some might suggest that you make MyGenericClass abstract, forcing any instantiation to be like this:
    MyGenericClass<String> entity = new MyGenericClass<String>() {};That would indeed cause the String type parameter to be available at runtime, since you're creating an anonymous inner class. But it leads to a convoluted and extremely statically expensive instantiation pattern. Using the class object is a better solution IMO.

  • Error in converting character string to smalldatetime data type

    I've installed SQL Server 2000 on my new laptop and Crystal Report XI, out of sudden, the Crystal Report to certain view can't run and I got the following error:
    Details: 22007 [Microsoft][ODBC SQL Server Driver][SQL SERVER]Syntax Error cnverting character string to smalldatetime data type.
    Any suggestions?
    Hannah

    Here is the view the err is complaining about:
    SELECT     TOP 100 PERCENT Cur.Closed_Month, Cur.Closed_Year, Cur.Incidents_Closed, Prev.Incidents_Closed AS PrevIncidents_Closed,
                          YrAgo.Incidents_Closed AS YearIncidents_Closed
    FROM         (SELECT     Closed_Month, Closed_Year, Incidents_Closed
                           FROM          dbo.Incidents_Closed) Cur INNER JOIN
                              (SELECT     Month(CONVERT(datetime, CAST(closed_month AS varchar) + '/01/' + CAST(closed_year AS varchar), 101) + 32) AS PrevMonth,
                                                       year(CONVERT(datetime, CAST(closed_month AS varchar) + '/01/' + CAST(closed_year AS varchar), 101) + 32) AS PrevYear,
                                                       Incidents_Closed
                                FROM          dbo.Incidents_Closed) Prev ON Cur.Closed_Month = Prev.PrevMonth AND Cur.Closed_Year = Prev.PrevYear INNER JOIN
                              (SELECT     Month(CONVERT(smalldatetime, CAST(closed_month AS varchar) + '/01/' + CAST(closed_year AS varchar), 101) + 366) AS PrevMonth,
                                                       year(CONVERT(smalldatetime, CAST(closed_month AS varchar) + '/01/' + CAST(closed_year AS varchar), 101) + 366) AS PrevYear,
                                                       Incidents_Closed
                                FROM          dbo.Incidents_Closed) YrAgo ON Cur.Closed_Month = YrAgo.PrevMonth AND Cur.Closed_Year = YrAgo.PrevYear
    What confused me is that it works fine with my previous laptop. I wonder if there is any patch in Crystal Report or SQL server that used to support certain functions but not support them anymore....
    Thanks
    Hannah

  • 1067: Implicit coercion of a value of type String to an unrelated type

    Hi,
    I created a webservice based on sql server 2005 with several methods successfully.
    I am having headach now just trying to do some simple tests with Flex :-(
    I used the "Import WebService", it created some code "generated webservices".
    My test method p_SEARCH_NAME_SOUNDEX is based on a sql procedure wich take a varchar (128) as a parameter => NAL_NOM.
    I am just trying to debug this function (error at line in red)
           public function searchEntry(name:String):void
                // Register the event listener for the findEntry operation.
                //agenda.addfindEntryEventListener(handleSearchResult);
                myWS.addp_SEARCH_NAME_SOUNDEXEventListener(handleSearchResult);
                // Call the operation if we have a valid name.
                if(name!= null && name.length > 0)
                   myWS.p_SEARCH_NAME_SOUNDEX(name);
    I got this error message:
    067: Implicit coercion of a value of type String to an unrelated type generated.webservices:NAL_NOM_type1.
    FLEX has creaetd a type called NAL_NOM_type1 for my class:
    * NAL_NOM_type1.as
    * This file was auto-generated from WSDL by the Apache Axis2 generator modified by Adobe
    * Any change made to this file will be overwritten when the code is re-generated.
    package generated.webservices
        import mx.utils.ObjectProxy;
        import flash.utils.ByteArray;
        import mx.rpc.soap.types.*;
         * Wrapper class for a operation required type
        public class NAL_NOM_type1
             * Constructor, initializes the type class
            public function NAL_NOM_type1() {}
            public var varchar:String;public function toString():String
                return varchar.toString();
    I tried to do myWS.p_SEARCH_NAME_SOUNDEX(NAL_NOM_type1(name));
    and also declared "name" as NAL_NOM_type1... but i still get this error.
    This is how it declared my webservice method:
            public function p_SEARCH_NAME_SOUNDEX(nAL_NOM:NAL_NOM_type1):AsyncToken
                 var _internal_token:AsyncToken = _baseService.p_SEARCH_NAME_SOUNDEX(nAL_NOM);
                _internal_token.addEventListener("result",_P_SEARCH_NAME_SOUNDEX_populate_results);
                _internal_token.addEventListener("fault",throwFault);
                return _internal_token;
    I am even not on the level of assigning the data to my grid... i just want to see how it gets the data first in debug.
    Thanks in advance for you help.
    kr,
    Meta

    Thanks _Natasha_
    I tried this:
    var t = new NAL_NOM_type1();
    t.varchar = name;
    myWS.p_SEARCH_NAME_SOUNDEX(t);
    It passes the 1st step :-) but I get another error now :-/
    I think it try to get back NAL_NOM_type1 from the server of course on the WSDL side it know only NAL_NOM
    Error: Cannot find definition for type 'http://NABSQL64DEV/::NAL_NOM_type1'
        at mx.rpc.xml::XMLEncoder/encodeType()[C:\autobuild\3.2.0\frameworks\projects\rpc\src\mx\rpc \xml\XMLEncoder.as:1426]
    I guess I have to change my constructor type... i am not used to these stuff :-s
    is this generating method the best way to access your data with webservices?
    the turorials I saw are xml file or array based... is there any link similar to my issue so I can learn better?

  • Any Java built in function to get the Class type corresponding to primitive

    I know it sounds strange but basically I have a Class and a String (I'm reading values from an XML file).
    If the Class is a primitive type (boolean, byte, char, short, int, long, float, and double) I would have to convert the String into the corresponding types.
    So I know how to do stuff like
    Integer.parseInt("22");but for all the primitive types is there some method where I can simply get a way to do that without writing a whole bunch of if statements?

    You could set up a class to parse your String. You could check to see if it contains a decimal point, if so then you check to see if it is less than float.MAX_VALUE etc same for the Integer family and you could use equals method to check if it is true or false.
    one other way would be to use parseInt etc and catch exceptions if there is an error, this is a bad idea though and a dirty way to do things.
    As suggested, maybe you have some idea of what data type your expecting and can limit the amount of parsing you have to do. Another way is to group all numeric values as doubles.
    You could start with something like this adding other methods checking the max value of the data types.
    public class StringParser
         public static void main(String[] args)
              String test = "1.0";
              System.out.println(containsDecimal(test));
              if (containsDecimal(test))
                   decimalSizeFinder(test);
              else
                   integerSizeFinder(test);
         static boolean containsDecimal(String input)
              for(int i=0; i<input.length(); i++)
                   if (input.charAt(i) =='.')
                        return true;
              return false;
         static void integerSizeFinder(String input)
              long value = Long.parseLong(input);
              if(value <=Byte.MAX_VALUE)
                   byte b = (byte)value;
              else if(value <= Short.MAX_VALUE)
                   short s = (short)value;
              else if(value <=Integer.MAX_VALUE)
                    int i = (int)value;
              //etc
            //Add code to assign the value to a variable someplace
         static void decimalSizeFinder(String input)
              double value = Double.parseDouble(input);
              if(value <=Float.MAX_VALUE)
                   float f = (float)value;
           //Add code to assign the value to a variable someplace
    }Message was edited by:
    kikemelly
    Message was edited by:
    kikemelly

  • Seemingly unpredictable results when calling an overriden parent method on an instance of a child class casted to the parent class

    I have a parent class with a sub-vi Override.vi, and a child which overrides this sub-vi.  I create an instance of this child.  I cast this child to it's parent class and store it in an array.  Later, if I invoke the parent's 'Override.vi' on this child (casted to parent) then Labview 2013 seems to randomly choose whether to run the parent or the child override.vi.  In Labview 2011 SP1 it would always call the childs version of override.vi (which while surprising to me was very useful).  This has totally broken an application I have been developing, any insight as to how to control which override.vi is run would be helpful (re-casting to the child class isn't really an option, as there are in fact many child classes each with their own version of override.vi).

    The actual data type of the wire is irrelevant in deciding which VI to run. The only thing that is relevant is the class of the object which is actually on the wire, so casting to the parent should not be relevant. *IF* the object really is a child, then LV should always call the child's VI, just like you say it works in 2011.
    I suspect that what's happening in your case is that somewhere you're generating a parent and that's what's actually on the wire (e.g. maybe you have an error somewhere and a function outputs the default value, which is a parent). The fact that it didn't happen in 2011 doesn't mean it's a bug in 2013. It could be that something else has changed.
    In any case, it's impossible to tell whether this is a misunderstanding, a bug in your code or a bug in LV without actual code. If you can post actual code which shows this, people can help. Otherwise (if it only happens in code you don't want to publish), you should try contacting NI directly so that you can at least show them the code.
    Try to take over the world!

  • When I chage node Name in jtree. It's casted String object

    Hello
    My English ability is very poor sorry
    now I make a tree
    and
    jtree.setEditable(true);
    I change my tree node's value
    from
    -root
    |-Hello
    to
    -root
    |-Hi
    after I chaged the value
    the value's class type is String
    I wan't to same class before change.
    How can I do?
    thank you

    Hi! Take a look at treeCellEditors in Java Tutorial. You need to provide custom TreeCellEditor.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • Cast string to char

    Hello;
    Could anyone tell me how to cast a string to char?
    for example;
    String [] args = {"test", "hello","a"};
    how can I cast the args[2] to char = 'a';
    Thanks

    Hello;
    Could anyone tell me how to cast a string to char?
    for example;
    String [] args = {"test", "hello","a"};
    how can I cast the args[2] to char = 'a';
    Thanks
    If you want to cast a String to a char you cannot. There are some conditions for casting. You just cannot cast anything primitive or object type to anything. how ever if you want to convert a String to a char array you could d othat as follows
    refer to String API
    public char[] toCharArray()
    Converts this string to a new character array.

  • Cast to a user class

    Hi.
    Suposse that I have got a class "MyClass" and then i add an object of "MyClass" into a container. If i retrieve all the component of the container with the method container.getComponents() i cant cast the component that i am stored in the array into "MyClass". How can i do it?? Do you know a way to do it??
    Thank you.

    MyClass must extend Component to have any chance at working. Even if MyClass extends Component, I believe you can not cast an array of one type to an array of another, even if the elements of the array have a relationship that allows the cast. For example...
    Component[] comps = new Component[2];
    comps[0]=new TextField();
    comps[1]=new TextField();
    TextField[] obs = (TextField[]) comps;
    Even though a TextField is a Component, and the elements of the array are TextFields, you get a class cast exception if you run the above code. The getComponents() method returns an array of Components so I believe you will have to cast each element.

  • RE:  Set Table Column Class Type

    Hi, there,
    Right now I try to set column class type and in this way my table sort class can check integer column and sort like interger not string (1,3,20 not 1,20,3).
    My problem is there is no setColumnClass method in AbstractTableModel.
    How can I do it??
    Thank you very much!!
    Xin

    There probably is a better solution.
    But I overloaded the getColumnClass(int ColumnIndex) function in the Table Model and return different classes depending on the Column selected...
    javax.swing.table.DefaultTableModel model =
    new javax.swing.table.DefaultTableModel(){
    public Class getColumnClass(int columnIndex)
    if(columnIndex == 6) //or whatever column you Choose
    return Integer.class;
    if(columnIndex == 3)
    return Integer.class;
    else
    return String.class;
    TableSorter sorter = new TableSorter(model);
    javax.swing.JTable table = new javax.swing.JTable(sorter);
    I hope this helps...

  • Use cast('12345' as tab.col%type) as a substr - PLS-00220

    Hello,
    I like to make sure that my constructed string fits into my variable, in a flexible way.
    The variable is like
    declare  t_comment tab.col%type; -- tab.col%type = varchar2(4)
    and in the PLSQL I would like to do concat a string and make sure it fits in my variable, just cut the right end if it is too long. I want it to be dynamic, so NOT
    t_comment := substr('1234567', 1, 4)
    CAST () works like a substring operator if casting to a smaller data type, but also leads to hardcoding.
    t_comment := cast ('1234567' as varchar2(4))
    But I want
    t_comment := cast ('1234567' as tab.col%type)
    But that gives me a
    PLS-00220: simple name required in this context.
    And when I define a subtype
    subtype comment_type is tab.col%type;
    t_comment := cast ('1234567' as comment_type)
    gives me a 
    PLS-00382: expression is of wrong type
    The documentation is also clear:
    CAST converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value.
    But it would be so nice to prevent hardcoding, to the varchar2(4) datatype in this case.
    Any suggestions on how to make this flexible?

    Hello,
    you can read the column length from the data dictionary and then use it in your SUBSTR instead of the hard coded value:
    SELECT data_length
    INTO v_length
    FROM user_tab_cols
    WHERE table_name = 'TAB'
    AND column_name = 'COL';
    t_comment := SUBSTR('1234567', 1, v_length);
    Not as simple as a %TYPE, but just as flexible.
    Regards
    Marcus

  • Valid attribute-class types for af:regionDef ?

    The only example or documentation I can find related to attributes of a regionDef are in /tagdoc/core/regionDef.html where there is an example which uses attributes of type String. Is it possible to use other classes? Any special syntax required in the EL expressions which use them? In another thread the following was suggested:
    <af:commandButton text="Save"
    action="#{sessionScope[regionAttrs.pageBeanName].save}"/>
    where pageBeanName is an attribute of type String.
    Unfortunately the page beans are mixed amoung the session and request scopes. Is there a way to pass in the scope or the actual pageBean? Alternatively I guess I could bind the action to a method with exception handling code so each scope could be checked in turn until the page bean was located but that seems a little heavy handed.

    To answer my own question ;-)
    Yes you can use other class types. Specifically I figured out how to use a Bean and more genericly a Java Interface (to which I passed the Bean). For example:
    <faces-config>
    <component-type>oracle.adfdemo.region.clientPageFooter</component-type>
        <component-class>
          oracle.adf.view.faces.component.UIXRegion
        </component-class>
        <component-extension>
          <region-jsp-ui-def>/regions/clientPageFooter.jspx</region-jsp-ui-def>
        </component-extension>
        <attribute>
          <attribute-name>pageBean</attribute-name>
          <attribute-class>demoOne.ClientPageFooter</attribute-class>
          <attribute-extension>
            <required>true</required>
          </attribute-extension>
        </attribute>
      </component>
    </faces-config>
    package demoOne;
    public interface ClientPageFooter
      public String save();
      public String reset();
    public class ClientDetailPage implements ClientPageFooter
      public String save()
        return "returnToClientList";
      public String reset()
        return null;
      <af:regionDef var="regionAttrs" >
                  <af:commandButton text="Reset"
                                    action="#{regionAttrs.pageBean.reset}"/>
                  <af:commandButton text="Save"
                                    action="#{regionAttrs.pageBean.save}"/>
                  <af:commandButton text="Cancel" action="returnToClientList"/>
      </af:regionDef>
              <af:region regionType="oracle.adfdemo.region.clientPageFooter"
                       id="clientPageFooter">
                <f:attribute name="pageBean" value="#{ClientDetailPage}"/>
              </af:region>Hope that helps someone :-)

  • Atg-rest-param-class-types

    I am using something like this as input to an ATG rest webservice which does validation with an array input.
    But i am not sure how to receive it in a formhandler especially from request.
    {'atg-rest-param-class-types':{'container-class':
    'java.util.ArrayList','element-class':
    'java.lang.String'},'arg1':['sit','stay','speak']}
    Pls help.
    Should i use JSON input customizer?

    Hi,
    By receiving you mean you want to receive the output of this request which is in the form an array. In this case you can use atg-rest-output and type should be JSON. The output will parse itself into JSON. You'll not need Output Customizer for this.
    Regards,
    RahulV

Maybe you are looking for

  • Error -  The exception, which is assigned to class 'CX_WDR_RT_EXCEPTION'

    Hi All, I get the following error when getting parameters from HTML Form to ABAP Webdynpro Application. Short text                                                                                An exception occurred that was not caught.   What happen

  • File to sync bapi_multimapping_without bpm

    Hi All, I have done a file ->bapi -> response to file testing interface using the adapter modules. My actual scenario is : Source file has multiple lines and for each line i have to call a bapi. The response of the BAPI needs to be appended in a file

  • Verizon World Plan 500_tracking used minutes

    Since I have subscribed above plan I am not able to track used minutes. The website to check is missing the spot to click. Different talks to Technical Service have not solved the problem. Last week Rep told me that they working on my problem.

  • Question about GRT54GS Versions.

    I'm wondering whats the difference between "GRT54GS v5" and "GRT54GS v6"?  Is there a site anyone knows which tells what was added to the new versions? I'm just a little curious because I just bought a new one and it was v5; was there something wrong

  • Smart form downloaded into .xml file ??.

    Hi all, When a smart form is downloaded, it gets downloaded as a .xml file. My question is, how does it get converted to .xml file. <i>Is there any</i> <u>function module</u> that is called and <i>if so</i> <u>what</u> is the function module.