简体   繁体   中英

Given an Object that is a primitive array, what is the most efficient way to determine the primitive type of the array elements

I have a method that needs to operate on a very general message. It receives an Object. I can determine if the Object is an array with:

obj.getClass().isArray()

but after that I need to find what the type of the array elements are.

My code will ultimately be passing data one element at a time to a system that will be re-building it's own data structure and I need to tell it what type it should be using. Eg imagine a JSON or XML message to something else and I need to tell that service how it should treat the data that was given to it in the message:

long [] data = { 42 };
processObject(data);

void processObject(Object obj) { ... }

will produce something like:

<msg>
   <value>42</value>
   <type>LONG</type>
</msg>

There is only one int type in all of java, which therefore means there is only one int[] type. Thus, it is as simple as:

if (obj instanceof int[]) {
   doSomethingWithIntArray((int[]) obj);
}

Or if you somehow want it in terms of class: if (obj.getClass() == int[].class) { .

If you want an enum, it's a simple matter of 8 if/elseifs. You can also make: Map<Class<?>, EnumType> , loading it up with a static initializer / using Map.of`:

private static final Map<Class<?>, EnumType> TYPES = Map.of(
  int[].class, EnumType.INT,
  byte[].class, EnumType.BYTE,
  ....);

and then you can call EnumType primitiveType = TYPES.get(obj.getClass()); which returns null if it's not a primitive array, and the EnumType you wanted if it is.

The if/elseif seems less efficient (8 steps, instead of the 1 step that TYPES.get would do), but is probably an order of magnitude or two faster. Far less overhead, CPUs pipeline, 8 chained ifs is nothing.

You want 'most efficient' and then talk about JSON and XML. Two formats that are quite, to notoriously, inefficient.

If you want to improve throughput and the like, you're barking up the wrong tree here. Making the java mode more efficient is going to speed up the process by at most 0.00000001%. Use a protocol designed for fast throughput (such as protobuf or something else binary oriented) if efficiency is what you're after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM