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.

Similar Messages

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

  • 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

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

  • 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

  • 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 );
    }

  • 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

  • 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

  • Getting the class of a primitive type or void

    Hello,
    Class.forName cannot be used to get the class of a primitive type or void. What does then ???
    I thought of defining a class for each primitive type and override getClass() to return the required type, but getClass() is final ...
    Please help

    I don't understand what you mean e.g.I get the name of the primitive type at runtime and need to convert it to a class. For example, Class.forName("byte") returns byte.class. But, unfortunately, Class.forName() doesn't return classes of primitives or void.
    I already solved the problem through putting ptimitive classes in a hashtable. But I was wondering if there is a simpler solution !!!

  • Kindly tell me authorization object for MRP type

    Hi friends,
    Kind tell me what is the authorization object for MRP type in material master.
    Your help is considered more important.
    thanks in advance
    willaims

    Hi Willaim,
    There is no standard authorization object for MRP type.
    Regards,
    Alexander

  • Kindly give authorization object for mrp type in material master

    Hi friends,
    Kind tell me what is the authorization object for MRP type in material master.
    Your help is considered more important.
    thanks in advance
    willaims

    hi,
    check your authorisation objects here:
    Go to PFCG --> Environment (at menu bar) --> authorization objects --> Display...
    Here see for MRP and MM for material managament in the tree structure...
    Regards
    Priyanka.P

  • How to convert an array collection instance to a complex object for interaction with webservice

    Hi there,
    I have a stubborn problem that I am trying to work out the best way to solve the problem.  I am interacting with a WebService via HTTPService calling a method called find(String name) and this returns me a List of ComplexObjects that contain general string and int params and also lists of other Complex Objects.  Now using the code:
    ArrayCollection newOriginalResultsArray = new ArrayCollection(event.result as Array)
    flex converts my complex objects results to an arraycollection so that I can use it in datagrids etc.  Now up until this part is all good.  My problem is when getting a single instance from the results list, updating it by moving data around in a new datagrid for example - I want to interact with the webservice again to do an create/update.  This is where I am having problems - because these webservice methods require the complex object as a parameter - I am struggling to understand how I can convert the array collection instance back to my complex object without iterating over it and casting it back (maybe this is the only way - but I am hoping not).
    I am hoping that there is a simple solution that I am missing and that there is some smart cookie out there that could provide me with an answer - or at least somewhere to start looking. I guess if I have no other alternative - maybe I need to get the people who built the service to change it to accept an array - and let them do the conversion.
    Any help would be greatly appreciated.
    Bert

    Hi Bert,
    According to my knowledge you can use describeType(Object) method which will return an XML... That XML will contain Properties and values just iterate through the XML and create a new Object..   Probably u can use this method...
    public function getObject(reqObj:Object,obj:Object,instanceName:String,name:String=null,index:int=-1):Obj ect
                if(!reqObj)
                    reqObj = new Object();
                var classInfo:XML = describeType(obj);
                var className:String = instanceName;
                if(name!=null)
                    className=name+"."+className;
                if(index!=-1)
                    className=className+"["+index+"]";
                for each (var v:XML in classInfo..accessor)
                    var attributeName:String=v.@name;
                    var value:* = obj[attributeName]
                    var type:String = v.@type;
                    if(!value)
                        reqObj[className+"."+attributeName] = value; 
                    else if(type == "mx.collections::ArrayCollection")
                        for(var i:int=0;i<value.length;i++)
                            var temp:Object=value.getItemAt(i);
                            getReqObject(reqObj,temp,attributeName,className,i);
                    else if(type == "String" || type == "Number" || type == "int" || type == "Boolean")
                        reqObj[ className+"."+attributeName] = value; 
                    else if (type == "Object")
                        for (var p:String in value)
                            reqObj[ className+"."+attributeName+"."+p] = value[p];
                    else
                        getReqObject(reqObj,value,attributeName,className);
                return reqObj;
    Thanks,
    Pradeep

  • How to get CLASS name for the generic item?

    Hi,
    I wrote following method to create a service instance.
    public static <IType> IType GetServiceInstance()
           IType type=null;
            try
            InitialContext ic=new InitialContext();
    //ERROR:      type=   ic.lookup(IType.class.getName());
            catch(Exception ex)
            //do handle
            return type;
        }please see the //Error: here its giving error, also i m not getting "class" variable in IDE!!!
    i want use like this;
    IUserService userService=ServiceFactory.GetServiceInstance<IUserService>();so how can i do this?
    Edited by: Manikandan.Java on Oct 31, 2007 3:02 AM

    I don't know if I understand your question, but you cannot find the class name because it is in run time just an object. You can, however, check if it is an instanceof.
    if (genericType instanceof MyType) {
         doMyThing();
    }

  • 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

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

Maybe you are looking for

  • Using DNS Services on an internal network and still using an outside DNS

    I have just started using Mac OSX Server for the first time and I am trying to set up an internal DNS server so I can set up an LDAP Directory master and replica. However, I am running into some problems in setting up the DNS server on our network. T

  • How to avoid printing an additional blank page at the end of the report

    I have a report which has 3 panels in the main section of the report, about 3 pages in size. 1st & 2nd panels are enclosed in a repeating frame, and 3rd panel in a different repeating frame. The vertical panels per page in the property inspector of t

  • Is anyone having problem with ringtone repeatition????

    I m facing this problem from the day i have buy dis iPhone 4s....its very irritating when u listen any message tone in a repeatition voice.....

  • [SOLVED] Broken setup after upgrading to 2.6.29

    I am running a x86_64 system. I have been running kernel26-2.6.28.7-2 for a while now. Upgrade to kernel26-2.6.28.8-1 caused some problem for me so I installed the older version from /var/cache/pacman/pkg/. After upgrading day before yesterday to 2.6

  • Connection timeout when running web service

    I'm running a desktop application which call an a web service every 10 minutes. Every few calls to this web service it fails. (for example: 4 calls to ws works fine but fifth call failed) When executing the application on: windows xp professional (ph