Primitive type reflection ?

Can anyone tell me how to check the type of a variable ?
I know that 'instanceof' is to check non primitive type and expense,
how about primitive type.
say
short some = 1.2;
how to know the type os 'some' after ?

If it's a field, you can get the class containing it using ClassName.class, and then call getDeclaredField on that class. Then Field has a method getType IIRC, and you can compare the type of the field with short.class.

Similar Messages

  • Reference to primitive types?

    I want to write a GUI that is able to set parameters to classes without knowing the exact nature of parameters. The parameter types are restricted to int and String. Something like this:
    ...in GUI class:
    ClassToConfigure c = getFromSomewhere();
    for (int i=0; i<c.getPropertyCount(); i++) {
      addToGUI(c.getDescription(), c.getType(), c.getKeyName())
    then later after the value is set in the GUI:
    c.setProperty(keyName, newValue);the setProperty method would have implementations for each type of newValue, and the GUI would have editing capabilities for each type too.
    My problem is that I do not know how to implement this in the ClassToConfigure (CTC). My thoughts were: CTC enumerates all field it wants to be configurable in its constructor, something like:
    addProperty(actual_field, "int", "Some description", "UniqueName");the CTC class would have a list of all properties with the "references" to the actual field to be able to update them.
    but then I don't know how to update the fields when CTC.setProperty() is called. Is there a way to keep a reference to a field, even if the field has a primitive type? Another way to do it would be using function pointers, passing the getter and setter to CTC.addProperty, but this isn't possible in java.
    Is there any straightforward way of implementing such behavior in java without tricky use of reflection?
    Thanks in advance,
    -Lev
    P.S. I hope I made my point understandable, if not please let me know and I'll try to rephrase my concern.

    I did not understand what you meant. But you can have the OO equivalents to function pointers, and that is method references. (But that is part of the the java.lang.reflect package)
    Kaj

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

  • Need suggestion for variable size array of primitive type.

    Hi all,
    I am working on a problem in which I need to keep an array of primitive (type int) sorted. Also I insert new elements while keeping it sorted, and at times I merge two similar arrays with unique elements.
    I would welcome suggestions on the implementation aspects as to which type/class to use. My primary consideration is performance. Here are my observations:
    1. type int
    Efficient operation, but arrays are fixed size so it makes clumsy code and overhead when the array is expanded or merged with another.
    Methods in class Arrays can be used, incl. binary search and sort.
    2. Vector, ArrayList, List, LinkedList
    Accept objects only. I can use Integer instead of int, but it will involve overhead, and I'll need to write my own sort and search routines (already done).
    For now, I choose option 2 using Vectors. Is there a better choice, or are there other options, given the conditions and consideration enumerated at the beginning?
    Appreciate any input or comments.

    mathmate wrote:
    I have not had the occasion to use them in parallel to recognize the difference. It pays to talk to people!A small benchmark is easily constructed:
    import bak.pcj.list.IntArrayList;
    import java.util.Random;
    import java.util.ArrayList;
    public class CollectionTest {
        static void testObjectsList(ArrayList<Integer> list, int n, long seed) {
            long start = System.currentTimeMillis();
            Random rand = new Random(seed);
            for(int i = 0; i < n; i++)
                list.add(new Integer(rand.nextInt()));
            for(int i = 0; i < n/2; i++)
                list.remove(rand.nextInt(list.size()));
            long end = System.currentTimeMillis();
            System.out.println("objectsList -> "+(end-start)+" ms.");
        static void testPrimitiveList(IntArrayList list, int n, long seed) {
            long start = System.currentTimeMillis();
            Random rand = new Random(seed);
            for(int i = 0; i < n; i++)
                list.add(rand.nextInt());
            for(int i = 0; i < n/2; i++)
                list.remove(rand.nextInt(list.size()));
            long end = System.currentTimeMillis();
            System.out.println("primitiveList -> "+(end-start)+" ms.");
        public static void main(String[] args) {
            long seed = System.currentTimeMillis();
            int numTests = 100000;
            testObjectsList(new ArrayList<Integer>(), numTests, seed);
            testPrimitiveList(new IntArrayList(), numTests, seed);
    }In the test above, Java's ArrayList is about 5 times faster. But when commenting out the remove(...) methods, the primitive 3rd party IntArrayList is about 4 to 5 times faster.
    Give it a spin.
    Again: just try to do it with the standard classes: if performance lacks, look at something else.

  • Array Of Primitive Type (kodo3.4)

    Hello,
    I want to map an array of primitive type (double[] or double[][] or...) to
    a blob, so I specified the mapping this way:
    <extension vendor-name="kodo" key="jdbc-field-map-name" value="blob">
    <extension vendor-name="kodo" key="column" value="DATA"/>
    </extension>
    As I use MySQL and not to have an exception, I have added:
    kodo.jdbc.DBDictionary: DriverDeserializesBlobs=false
    But when I tried to refresh using kodo.jdbc.meta.MappingTool, I get:
    [refresh] Exception in thread "main" kodo.util.FatalInternalException:
    Cannot map "fr.ifp.reservoir.model.business.geostat.Lithotype.facies".
    Check the class and make sure you are using only supported types.
    [refresh] at
    kodo.jdbc.meta.DynamicMappingProvider.createFieldMapping(DynamicMappingProvider.java:336)
    [refresh] at
    kodo.jdbc.meta.DynamicMappingProvider.getFieldMapping(DynamicMappingProvider.java:118)
    [refresh] at
    kodo.jdbc.meta.MappingRepository.getFieldMapping(MappingRepository.java:470)
    [refresh] at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:993)
    [refresh] at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:973)
    [refresh] at
    kodo.jdbc.meta.AbstractClassMapping.getMappings(AbstractClassMapping.java:939)
    [refresh] at
    kodo.jdbc.meta.AbstractClassMapping.getDeclaredFieldMappings(AbstractClassMapping.java:659)
    [refresh] at
    kodo.jdbc.meta.AbstractClassMapping.resolve(AbstractClassMapping.java:801)
    [refresh] at
    kodo.jdbc.meta.BaseClassMapping.resolve(BaseClassMapping.java:341)
    [refresh] at
    kodo.jdbc.meta.MappingRepository.resolve(MappingRepository.java:431)
    [refresh] at
    kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:349)
    [refresh] at
    kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:177)
    [refresh] at kodo.jdbc.meta.MappingTool.refresh(MappingTool.java:591)
    [refresh] at kodo.jdbc.meta.MappingTool.run(MappingTool.java:941)
    [refresh] at kodo.jdbc.meta.MappingTool.run(MappingTool.java:879)
    [refresh] at kodo.jdbc.meta.MappingTool.main(MappingTool.java:802)
    Thanks for your help.
    nicolas

    Hi,
    No more succes with persistence-modifier="persistent"...
    My class:
    public class ArrayWrapper {
    private String name;
    private double[] array;
    public ArrayWrapper(String name, double[] array) {
    this.name = name;
    this.array = array;
    public double[] getValues() {
    return array;
    public String getName() {
    return name;
    My metadata file:
    <jdo>
    <package name="model">
    <class name="ArrayWrapper">
    <field name="array" persistence-modifier="persistent">
    <extension vendor-name="kodo" key="jdbc-field-map-name" value="blob">
    <extension vendor-name="kodo" key="column" value="DATA"/>
    </extension>
    </field>
    </class>
    </package>
    </jdo>
    My StackTrace:
    refresh-mapping:
    [java] Exception in thread "main" kodo.util.FatalInternalException:
    Cannot map "model.ArrayWrapper.array". Check the class and make sure you
    are using only supported types.
    [java] at
    kodo.jdbc.meta.DynamicMappingProvider.createFieldMapping(DynamicMappingProvider.java:336)
    [java] at
    kodo.jdbc.meta.DynamicMappingProvider.getFieldMapping(DynamicMappingProvider.java:118)
    [java] at
    kodo.jdbc.meta.MappingRepository.getFieldMapping(MappingRepository.java:470)
    [java] at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:993)
    [java] at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:973)
    [java] at
    kodo.jdbc.meta.AbstractClassMapping.getMappings(AbstractClassMapping.java:939)
    [java] at
    kodo.jdbc.meta.AbstractClassMapping.getDeclaredFieldMappings(AbstractClassMapping.java:659)
    [java] at
    kodo.jdbc.meta.AbstractClassMapping.resolve(AbstractClassMapping.java:801)
    [java] at
    kodo.jdbc.meta.BaseClassMapping.resolve(BaseClassMapping.java:341)
    [java] at
    kodo.jdbc.meta.MappingRepository.resolve(MappingRepository.java:431)
    [java] at
    kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:349)
    [java] at
    kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:177)
    [java] at kodo.jdbc.meta.MappingTool.refresh(MappingTool.java:591)
    [java] at kodo.jdbc.meta.MappingTool.run(MappingTool.java:941)
    [java] at kodo.jdbc.meta.MappingTool.run(MappingTool.java:879)
    [java] at kodo.jdbc.meta.MappingTool.main(MappingTool.java:802)

  • Conversion error with non-primitive types

    I'm wondering if anyone else is seeing this problem or has a potential solution.
    The problem, in a nutshell:
    I have beans that use non-primitive types (Float instead of float) in the getters and setters. However I keep getting conversion error problems. If I switch to primitive types, I don't get conversion errors. The built-in FloatConverter says (in the documentation at least) that it supports both primitives and boxed types. This was all working in EA4, though. I am discovering this problem as I migrate from EA4 to 1.0.
    The code is pretty straightforward:
    public class Bean implements Serializable {
    public float getProp() {...}
    public void setProp(float) {...}
    public Float getPropOld() {...}
    public void setPropOld(Float) {...}
    <!-- works -->
    <h:inputText id="floatinput" value="#{BeanInstance.prop}"/>
    <!-- doesn't work -->
    <h:inputText id="floatinputold" value="#{BeanInstance.propOld}"/>
    Any ideas? I have tried explicitly calling the FloatConverter but that gave the same problems.

    Okay, I figured out my problem.
    The JSF spec implies that f:convertNumber may be used inside an h:inputText tag. The early versions of Core JSF go further and show f:convertNumber being used inside an h:inputText tag in one of the examples. (Chapter 7, conversions).
    However, this has been the source of my problem. When using f:convertNumber, the converter would automatically determine the data type without regard to the data type in the backing bean. Hence, it would try to pass Longs or Doubles to the bean instead of Floats.
    I believe this may be an issue in the 1.0 FR release.

  • Primitive type Changing???

    One of my friends sent me this e-mail. Can anyone help??
    ok wood, here's one for you:
    the software i'm writing get's data from one of two processors on a
    satelite. these processors use different #'s of bytes for their
    primitive types.
    bool - 1 byte
    short - 2 bytes
    int - 2 bytes
    long - 4 bytes
    float - 4 bytes.
    so..as you know the jvm uses 4 bytes for an int, 8 for a long. I
    want to be able to have people who are developing sims ontop of my
    framework be able to use a primitiave type, such as an int, and have
    it only be 2 bytes...now i'm pretty sure this isn't possible. You
    can't overload a primitive type in java right? I have some ideas
    here on what to do (create whole new objects, holding byte arrays and
    use java.nio to manaage them), but it just seems like such a hastel.
    i guess i was wondering if you have ever seen this kindof thing
    before and if you had any advice. thanks man.

    In C, primitive types can vary in size, based on the platform being used. In Java, the size of primitives is static. If he wants 16-bit storage, short is the way to go. Well, a char is a couple of bytes, too, but it's unsigned, intended for Unicode characters, and probably not what he's looking for anyway...
    :o)

  • Configure array of primitive type for POF

    My impression is that Coherence's POF implementation can handle Java primitive and String by default thus we don't need to provide a customized POF configuration file if the object been put into the cache is Java primitive type.
    How about arrary of primitive type? For example, byte[]. Can Coherence's POF implementation handle byte[] as well?

    Just asking since we plan to move from using Externalizable to POF and not sure if we need special handling for byte[] type.
    Thanks for the reply.
    Regards,
    Chen

  • Java primitive types??

    What r the Java primitive types??What is it for?

    What exam or job interview are you studying for exactly? One day it's strange questions on EJB, an another JSF, on another some question about Servlets demonstrating a lack of fundamental understanding of web services and today primitives?
    Please give due consideration to actually learning Java properly and not just random bits and pieces. Your current style is not working for you as can be seen from the constant utter confusion of many of your questions and posts.

  • Primitive Types

    Why would you use a Long on a domain object instead of the long primitive type?

    if I needed access to the Long method I could always
    just wrap the long in a Long so maybe longs are the
    way to go as they use less memory and are faster.Unless you have a lot of long values, the memory consumption is unlikely to be important.
    How fast is it to add or remove a long value from a Domain Object? You might find you need to recompile the class and reload it. Not very fast at all.
    If your Domain Object have fixed primative values, you could use primative however domain objects are typically generic and dynamic.

  • Can a Data Bean hold a member of primitive type?

    My senior advices me not to use members of primitive types inside a data bean. Say like not to use a boolean, int etc...instead use a Boolean, Integer etc....
    but he doesnt give me a proper reason for the same, but juz says that itz all a part of a good design guideline.
    could u plz throw ur views on this....?

    Using the wrappers instead of the primitives allows you to use "null" to represent the absence of a value. That's often useful.

  • Cannot invoke toString on the primitive type int

    im trying to make a sudoku puzzle but having trouble with the arrays, ive got two arrays
    int [][] actual = new int [9][9];
        String [][] possible = new String [9][9];part of my code im trying to generate a sudoku board, this is the part of the error in
    public void possVals(int col, int row)
              if(possible[col][row].equals(""))
                   str = "123456789";
              else str = possible[col][row];
              for(r = 1; r < 9; r++)
                   if(actual[col][r] != 0)
                        str = str.Replace(actual[col][r].toString(), "");
              }could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' please

    ajp_08 wrote:
    could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' pleaseBut you can do like this
    int i = 12345;
    String s = Integer.toString(12345);So, the following should work
    str = str.Replace(Integer.toString(actual[col][r]), "");Good luck!
    Edited by: A.J.Bharanidharan on Nov 17, 2009 6:06 PM

  • Does TopLink support arrays of primitive types?

    Does TopLink support arrays of primitive types?

    You must use a collection.
    If you really wanted to you could store the data as an array and use get/set methods to convert between the array and collection, or customize your own ContainerPolicy, however arrays a very inefficent to add/remove from so TopLink only provides support for collections.

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

Maybe you are looking for

  • Help Urgent Toshiba 5005-S504

    I have a Toshiba 5005-S504 and tried updating the bios but  now be4 I tried updating it it turned off quite often I thought it might be the bios too and well I never updated but now when I try turning it on it starts loading windows normally and inte

  • How to pass selection screen parameters in text elements?

    how to pass selection screen parameters in text elements?

  • Srdemo doesn't work in web?

    I configured OAS and I could access to my project (Jdeveloper) at the local. For instance ; when the client users use this "http:\\localhost:7777\srdemo" link, they can access the project. But I can't configure our server to web like this. What can I

  • Just got back from exchanging

    Got a week 38 with Macy Gray...it's GORGEOUS! I hope iskin releases their case for it soon.

  • AVL report Display problem

    Hi, I am changing a stnadard report program. Its displying output as ALV list display. As per stnadard program its having 4 push buttons in the report out. I have to remove those and display the 'Change Layout' button in the output. I have deleted th