Get class object for primitive datatype name stored in a string

Hi,
I have an array of Strings:
String[] somePrimitives = {"int", "char", "void" };
I want to achieve the equivalent of :
for(int k = 0; k < somePrimitives.length; k++) {
Class myClass = Class.forName(somePrimitives[k]); //Wont work
We all know, we cannot do Class.forName("int") etc since "int" is not a path to
an actual class - whereas Class.forName("java.lang.Integer") will work.
Can anyone tell me how to achieve the above ?
Of course, I don't want to have numerous hardcoded checking conditions like
if(somePrimitives[k].equals("int")) return (Integer.TYPE);
thanks.

1. Why couldn't java provide me a simple provision to list all available primitives and their corresponding
class mapping ? Why should I do the mapping...shouldn't the language have taken care of
its provisions ?Yes, and native compilation on the fly, dynamic modification of classes, a sensible types system, usable Number tree, quasiquotation, access to the AST of the source, getting a method based on argument types rather than parameter types, etc. etc.
2. Or even better they could have made the method
Class.getPrimitiveClass(String primitiveDatatTypeName)
as a public method. This would have solved the whole
problem with a one line piece of code. Why did they
have to make it non-public ???If you want it easy, go elsewhere.
But seriously, the reflection capabilities were tagged onto Java as it grew, and were not designed to reflect the state of the art, but as a 'just enough to get by' solution. Most of the time people don't need it, so it's not there, any you have to roll your own.
Pete

Similar Messages

  • Create array of arbitrary dimensions / get Class object for primitive types

    Here's an interesting problem: is there any way to code for the creation of an n-dimensional array where n is only known at runtime (input by user, etc.)?
    java.lang.reflect.Array has a newInstance method which returns an array of an arbitrary number of dimensions specified by the int[] argument, which would give me what I want. However, the other argument is a Class object representing the component type of the array. If you want to use this method to get an array of a primitive type, is it possible to get a Class object representing a primitive type?

    That doesn't help, since the whole problem is that the number of dimensions aren't known until runtime. You can't simply declare a variable of type int[][] or use an int[][] cast, since the number of []'s is variable.
    The int.class construction was partly what I was looking for. This returns the array needed (assuming some read method):
    int dimensions = read();
    int size = read();
    int[] index = new int[dimensions];
    for (int i = 0; i < dimensions; i++)
        index[i] = size;
    Object myArray = Array.newInstance(int.class, index);The only problem is, as an Object, I can't use myArray usefully as an array. And I can't use a cast, since that requires a fixed number of dimensions.

  • Arrays of arbitrary dimensions / Class object for primitive types

    Here's an interesting problem: is there any way to code for the creation of an n-dimensional array where n is only known at runtime (input by user, etc.)?
    java.lang.reflect.Array has a newInstance method which returns an array of an arbitrary number of dimensions specified by the int[] argument, which would give me what I want. However, the other argument is a Class object representing the component type of the array. If you want to use this method to get an array of a primitive type, is it possible to get a Class object representing a primitive type?

    Devil is in the detailspublic class Test2 {
      public static void main(String[] args) {
        Object[] myArray = new Object[10];
        fillDimensionalArray(myArray, 5, 5);
      public static void fillDimensionalArray(Object[] array, int dim, int size) {
        if (dim==1) {
          for (int i=0; i<size; i++) {
            array[i] = new int[size];
            for (int j=0; j<size; j++) ((int[])array)[j]=999;
    } else {
    for (int i=0; i<array.length; i++) {
    array[i] = new Object[size];
    for (int j=0; j<size; j++) {
    fillDimensionalArray( (Object[]) array[i], dim - 1, size);

  • To get Class object representing the primitive type by a String

    for classes,I can use
    classNameString = "java.lang.String"
    Class c=Class.forName(classNameString);
    to get Class object representing the classNameString.
    but to get Class object representing the primitive type ,I have to use something like :
    Class c=Integer.TYPE;
    is there any way to get Class object representing the primitive type by a String?

    not using Class.forName(). you'll just need to key off the String passed to see whether it names a primitive:class ClassUtilities {
       * Gives the <code>Class</code> corresponding to a named class or primitive.
       * @param  name  FQN of a class, or the name of a primitive type
       * @param  loader  a {@link java.lang.ClassLoader ClassLoader}
       * @return  the <code>Class</code> for the name given.  This method
       * converts primitive type names to their particular <code>Class</code>
       * object.  <code>null</code>, the empty string, <code>"null"</code>, and
       * <code>"void"</code> yield {@link java.lang.Void#TYPE Void.TYPE}.  If any
       * classes require loading because of this operation, the given
       * <code>ClassLoader</code> performs the loading.  Such classes are not
       * initialized, however.
       * @throws  ClassNotFoundException  if the name names an unknown class
       * or primitive
       * @see  java.lang.Class#getName
      static Class classForNameOrPrimitive( String name, ClassLoader loader )
        throws ClassNotFoundException {
        if ( name == null || name.equals( "" ) || name.equals( "null" ) || name.equals( "void" ) ) {
          return Void.TYPE;
        if ( name.equals( "boolean" ) )
          return Boolean.TYPE;
        if ( name.equals( "byte" ) )
          return Byte.TYPE;
        if ( name.equals( "char" ) )
          return Character.TYPE;
        if ( name.equals( "double" ) )
          return Double.TYPE;
        if ( name.equals( "float" ) )
          return Float.TYPE;
        if ( name.equals( "int" ) )
          return Integer.TYPE;
        if ( name.equals( "long" ) )
          return Long.TYPE;
        if ( name.equals( "short" ) )
          return Short.TYPE;
        return Class.forName( name, false, loader );
    }

  • Getting the objects for a class

    I am able to get all live classes of a dynpro by using method cl_gui_cfw=>get_living_dynpro_controls. (Also thanks to this forum).
    The resulting table has a reference to a class like ...
    How do I use this reference to:
    1. Get the objects for it?
    2. How can I then free the object from memory by using the "free" method.
    I guess I am asking how to dynamically assign it, then make sure it has a free method and then to use the method to actually free it.

    Hello Uwe
    My first reaction was "NO it cannot be that easy!!". It almost was but on the second line I get a short dump. Then I realised why: the other live control in the table was a sub class of the first class and as a result it was cleared on the first call.
    So I modified the call to be a recursive call (of the form) as follows...
    form clear_live_controls .
    DATA:
      gt_list       TYPE cnto_control_list,
      gt_wa like line of gt_list.
      REFRESH: gt_list.
      CALL METHOD cl_gui_cfw=>get_living_dynpro_controls
        IMPORTING
          control_list = gt_list.
      describe table gt_list lines tab_lines.
      if tab_lines = 0.
    *    Nothing
      else.
         loop at gt_list into gt_wa.
           gt_wa->free( ).
           exit.
         endloop.
         perform clear_live_controls.
      endif.
    endform.                    " clear_live_controls
    This took care of it.
    Many thanks for your help.
    Regards

  • While running my app I get the below error  - have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature

    I am running ATG[10.1.2] app on Jboss [EAP 5.1.0 GA] I am able to open dyn/admin however when I start my app I get the below error
    java.lang.LinkageError: loader constraint violation: when resolving method "atg.servlet.ServletUtil.setSessionConfNumCacheRequest(Ljavax/servlet/http/HttpServletRequest;)Ljavax/servlet/http/HttpServletRequest;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, atg/filter/dspjsp/PageFilter, and the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) for resolved class, atg/servlet/ServletUtil, have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature
      at atg.filter.dspjsp.PageFilter.doFilter(PageFilter.java:215)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ForwardFilter.doFilter(ForwardFilter.java:263)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ErrorFilter.doFilter(ErrorFilter.java:279)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:638)
      at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:446)
      at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
      at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
      at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:416)
      at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
      at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:286)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
      at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
      at java.lang.Thread.run(Thread.java:680)
    11:22:47,413 ERROR [[localhost]] Exception Processing ErrorPage[errorCode=500, location=/global/errorPage500.jsp]

    The supported JBoss version for 10.1.2 is JBoss EAP 5.1.2 but I don't think that your issue is caused because of this. Your issue is more of an environmental thing as you are probably getting two different versions getting loaded of class javax.servlet.http.HttpServletRequest and so correspondingly two different Class objects as the error shows. One reason for this could be if you include any server-specific libraries (in present case the Servlet API JAR which contains the class javax.servlet.http.HttpServletRequest) of a different version in the /WEB-INF/lib of your web application. Try removing it from there if so and see if that helps.

  • User defined class objects for a ADF component (button,inputfield)

    How do I define a user defined class object for ADF objects?
    My requirement is that when I do a modification to the class object, it should get reflectected to all the instances on my page.
    E.g:- I'm having class object clsInputField, and all my input fields in my pages are based on this object. So when I change clsInputField it should get reflected to all my controls based on this class object.
    Please help!!!

    Hi Timo,
    In our client server environment, we have a custom control for managing the zip code (used a Custom InputText field which extends the actual TextField) . All zip code specific validations are written in this custom class. In our application many of the pages uses this Custom component. So if any of the zipcode specific behaviour changes, we could implement this by only changing the Custom InputText field class.
    We need to implement this behaviour in our ADF applications. Please advise.
    Thanks,
    Vishnu

  • Need to get IRole object using Roles Display Name

    Hi,
    I need to get IRole object using Roles Display Name. I had the below code in EP 2004 SP12 and it works. But the same code dont work in EP 2004s SP13
    user = request.getUser();
    profile = request.getComponentContext().getProfile();     
    String strRoles = profile.getProperty("Roles");
    String strRole[] = strRoles.split(",");
    IRoleFactory roleFactory = UMFactory.getRoleFactory();
    String roleUniqueId = null;
    int i = 0;
    boolean flagRedirect = false;
    for(i = 0; i < strRole.length; i++){
         try
              com.sap.security.api.IRole role = roleFactory.getRoleByUniqueName(strRole<i>);
              roleUniqueId = role.getUniqueID();
              if(!user.isMemberOfRole(roleUniqueId, true))
                   continue;
              flagRedirect = true;                    
              break;
         catch(UMException ex)
         catch(IOException ex)
    if(!flagRedirect){
    Where property Roles will have comma separated roles display names like "com.ABC.ortho_reports,com.ABC.lawns_ortho_reports,com.ABC.executive_reports"
    Please advise.

    Thanks Mrudula for the response. Sorry for the delay in responding.
    I get UMEException with the message "Role with uniqueName com.ABC.general not found"
    But it works fine if i specify Role unique role (like pcd:portal_content/com.abc.Marketing_Workbench/com.abc.Roles/com.abc.general).
    We are in the process of upgrading Portal environment from EP6.0 SP12 to EP7.0 SP13. Above scenario works fine in the older environment.

  • Error while getting data objects for instance

    Hello Expert,
    I am getting some weird error - whenever there is a new process is triggered and I check context Data, I get following error -
    "Error while getting data objects for instance processinstanceid"
    Thanks is advance
    Priya

    Hi Priya,
    this is a known issue in the xml processing of the Java Virtual Machine. Please refer to the SAP Note for this issue: 1949395
    This should solve your issue.
    Best regards,
    Stefan

  • Get the objects for getDeclaredFields

    Hi,
    Can I get the objects of the Fields in my class.
    I want to go through my Fields and find the ones with a certain suffix in there name. This I have done with getDeclaredFields. But know I want to get and set the data for the corresponding objects.
    for (Field zField : getClass().getDeclaredFields())
        if (zField.getName().endsWith("_Save"))
             // I need somethign that will do something like this. I know the next lines don't work
             Object zObject = zField.getObject();
             if (zObject  instenceof jCheckBox)
                 ((jCheckBox)zObject).isSelected();
    }Thanks,
    Shaul

    Shaul wrote:
    I'm sorry. I didn't understand that the object is the one that contains the objects that I need.Exactly. And if the field is static you pass in 'null'

  • Container for primitive datatypes?

    Which is the best way to store primitive datatypes if I need the functionality to expand and shrink the container.
    I've tried to use Vector and Arraylist but I have to convert each datatype to it's wrapper and add them one by one.
    Aren't there some container which have a method like. Container.add(primitive[] myprimitive)?

    Sort of related: JDK 1.4 has some new IO packages that have primitive buffers for primitive types (java.nio). Not exactly what you're looking for, but just thought I'd throw in my two cents.
    Best bet is to write your own container that acts like a Vector, but only provide add and get methods which accept and return doubles/ints/etc.
    class DoubleContainer
      java.util.Vector vec = new java.util.Vector();
      public DoubleContainer()
      void add(double d)
        vec.add(new Double(d));
      double get(int index)
        return ( (Double)vec.get(index)).doubleValue();
      // some more methods might be needed here, like insert, remove...
    }

  • Generic way to get Document object for CS products

    Just going through the CS SDK documentation it appears, for each product - Photoshop, InDesign, Illustrator, InCopy - one has to
    get hold of a Document object that is tied to each product. In other words com.adobe.illustrator.Document for Illustrator and so on.
    It would be a life saver to have a base Document class that provides common properties across al CS products, ad have product
    specific Document class inherit from the common Document base class. That way developers could write more generic code
    that doesn't need to couple with the specific application so tightly. Is there such a class already ? Didn't find it in the CS SDK docs
    or the sdk itself.
    Also beyond the 4 products (Photoshop, InDesign, Illustrator, InCopy) how does one get hold of Document object for Flash Pro etc.
    Are there plans to add ActionScript support beyond the 4 products ?  There are ~ 15 products in CS and it seems we need to now use
    CS SDK and the old C++ sdk for the unsupported products in CS SDK, make sit hard to write apps that are cross platform and
    work seemlessly with all CS products.
    Oliver A @ Evolphin
    http://www.evolphin.com

    In Computer Science we say all problems can be solved by one more level of indirection . While each product has
    different scripting models, why can't a generic base class bridge them via a delegation pattern that invokes the product specific document method
    for common properties like document path, document folder etc. Product specific methods can be implemented as they are now I am just
    talking about common methods.
    For e.g.
       com.adobe.product.Document.getDocumentPath() ----> via derived clas soverride will call photoshop.Document.getDocumentPath()
    If generic base class is hard to implement how about a common interface to shield us from product specific details when not needed ?
    What we need is a generic interface or abstract class that provides gettters for common properties. This is OOPS 101, am I missing something
    here ?
    Again I am not saying this will work fo rall properties just for a few common properties would be a good start..
    Oliver @ A
    http://www.evolphin.com

  • What could be the query to get Spend Amount for a Product name in EBS?

    Hi Experts,
    I need a help to write a query in EBS to get Spend Amount for any given Product Name and Top Level Category (Segment1).
    It can be two different query or a single one. Please reply if anyone knows how to do it. I need it for testing purpose.
    Thanks in advance.

    All good here Sudipta.
    You can try the below SQL.
    SELECT msib.description,mcb.segment1,SUM(pla.quantity*pla.unit_price) total_spend
    FROM
    po_lines_all pla,
    mtl_categories_b mcb,
    mtl_system_items_b msib
    WHERE pla.category_id = mcb.category_id
    AND pla.item_id = msib.inventory_item_id
    AND msib.organization_id = <enter your item master organization id>
    GROUP BY msib.description,mcb.segment1
    If you don't want to use the PO_LINES_ALL, is there any other sourced you are planning to use for spend.
    SELECT mcb.segment1,SUM(pla.quantity*pla.unit_price) total_spend
    FROM
    po_lines_all pla,
    mtl_categories_b mcb
    WHERE pla.category_id = mcb.category_id
    GROUP BY mcb.segment1
    and do not need the po_lines_all table. I'm doing a data validation between OBIEE reports and EBS test data. In report i'm keeping only Product Name and Spend Amount to make it simple. Now I need to check the values are same in report and EBS. Thats the criteria.
    Thanks
    Sudipta

  • To get Lock object for Standard Table

    Hi all,
    i want to update table FKK_GPSHAD,so i need corresponding lock object for this table.can any one sughgest me the solution for this.
    Thanks in advance,...

    Hi,
    Lock objects are use in SAP to avoid the inconsistancy at the time of data is being insert/change into database.
    SAP Provide three type of Lock objects.
    Read Lock(Shared Locked)
    protects read access to an object. The read lock allows other transactions read access but not write access to
    the locked area of the table
    Write Lock(exclusive lock)
    protects write access to an object. The write lock allows other transactions neither read nor write access to
    the locked area of the table.
    Enhanced write lock (exclusive lock without cumulating)
    works like a write lock except that the enhanced write lock also protects from further accesses from the
    same transaction.
    You can create a lock on a object of SAP thorugh transaction SE11 and enter any meaningful name start with EZ Example EZTEST_LOCK.
    Use: you can see in almost all transaction when you are open an object in Change mode SAP could not allow to any other user to open the same object in change mode.
    Example: in HR when we are enter a personal number in master data maintainance screen SAP can't allow to any other user to use same personal number for changes.
    Technicaly:
    When you create a lock object System automatically creat two function module.
    1. ENQUEUE_<Lockobject name>. to insert the object in a queue.
    2. DEQUEUE_<Lockobject name>. To remove the object is being queued through above FM.
    You have to use these function module in your program.
    check this link for example.
    http://help.sap.com/saphelp_nw04s/helpdata/en/cf/21eea5446011d189700000e8322d00/content.htm
    tables:vbak.
    call function 'ENQUEUE_EZLOCK3'
    exporting
    mode_vbak = 'E'
    mandt = sy-mandt
    vbeln = vbak-vbeln
    X_VBELN = ' '
    _SCOPE = '2'
    _WAIT = ' '
    _COLLECT = ' '
    EXCEPTIONS
    FOREIGN_LOCK = 1
    SYSTEM_FAILURE = 2
    OTHERS = 3
    if sy-subrc 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
    Normally ABAPers will create the Lock objects, because we know when to lock and how to lock and where to lock the Object then after completing our updations we unlock the Objects in the Tables
    http://help.sap.com/saphelp_nw04s/helpdata/en/cf/21eea5446011d189700000e8322d00/content.htm
    purpose: If multiple user try to access a database object, inconsistency may occer. To avoid that inconsistency and to let multiple user give the accessibility of the database objects the locking mechanism is used.
    Steps: first we create a loc object in se11 . Suppose for a table mara. It will create two functional module.:
    1. enque_lockobject
    1. deque_lockobject
    before updating any table first we lock the table by calling enque_lockobject fm and then after updating we release the lock by deque_lockobject.
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21eea5446011d189700000e8322d00/content.htm
    GO TO SE11
    Select the radio button "Lock object"..
    Give the name starts with EZ or EY..
    Example: EYTEST
    Press Create button..
    Give the short description..
    Example: Lock object for table ZTABLE..
    In the tables tab..Give the table name..
    Example: ZTABLE
    Save and generate..
    Your lock object is now created..You can see the LOCK MODULES..
    In the menu ..GOTO -> LOCK MODULES..There you can see the ENQUEUE and DEQUEUE function
    Lock objects:
    http://www.sap-img.com/abap/type-and-uses-of-lock-objects-in-sap.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/cf/21eea5446011d189700000e8322d00/content.htm
    Match Code Objects:
    http://help.sap.com/saphelp_nw2004s/helpdata/en/41/f6b237fec48c67e10000009b38f8cf/content.htm
    http://searchsap.techtarget.com/tip/0,289483,sid21_gci553386,00.html
    See this link:
    http://www.sap-img.com/abap/type-and-uses-of-lock-objects-in-sap.htm
    Check these links -
    lock objects
    Lock Objects
    Lock Objects
    Please reward points if useful.
    Regards
    Rose

  • Using an array name stored in a String in a Statement

    In my sequence, I build an array in one section and store it in a variable called Locals.Test_Array.
    I build the name of the permanent place I would like to store this array and store it in a string called Locals.SG_Test_Array_Name.
    I would like to move the values from Locals.Test_Array to the Station Globals Array name stored in Locals.SG_Test_Array_Name.
    For example:
    the string stored in Locals.SG_Test_Array_Name is "StationGlobals.Coolant_Temperature_Test_Array" (already created in Station Globals)
    What I am trying to do is this:
    Statement                        StationGlobals.Coolant_Temperature_Test_Array=Loca​ls.Test_Array  (this works)
    The Station Global Array name needs to change as the sequence executes and the data in Locals.Test_Array changes.
    What I need is something like this.
    Statement                         Locals.SG_Test_A​rray_Name=Locals.Test_Array  (where SG_Test_Array_Name is a string that holds the name of the array)
    Thanks, Big_Will

    Evaluate(Locals.SG_Test_Array_Name + " = Locals.Test_Array " )

Maybe you are looking for