Determining If an Object Is of Primitive Type

Determining if an Object is of primitive type

The types in an Object[] will never really be primitive - because you've got references! Here the type of i is int whereas the type of the object referenced by o is Integer (due to auto-boxing).

It sounds like you need to find out whether the type is a "wrapper for primitive". I don't think there's anything built into the standard libraries for this, but it's easy to code up:

import java.util.*;

public class Test
{
public static void main(String[] args)
{
System.out.println(isWrapperType(String.class));
System.out.println(isWrapperType(Integer.class));
}

private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes();

public static boolean isWrapperType(Class<?> clazz)
{
return WRAPPER_TYPES.contains(clazz);
}

private static Set<Class<?>> getWrapperTypes()
{
Set<Class<?>> ret = new HashSet<Class<?>>();
ret.add(Boolean.class);
ret.add(Character.class);
ret.add(Byte.class);
ret.add(Short.class);
ret.add(Integer.class);
ret.add(Long.class);
ret.add(Float.class);
ret.add(Double.class);
ret.add(Void.class);
return ret;
}
}

Java: How to determine if type is any of primitive/wrapper/String, or something else

I found something:

Commons Lang: (would have to combine with check for String)

ClassUtils.isPrimitiveOrWrapper()

Spring:

BeanUtils.isSimpleValueType()

This is what I want, but would like to have it in Commons.

How to tell if a primitive type was cast into an object in Java?

What happens when you write Object x = 10

The int is autoboxed, which makes it into an Integer with value 10.

Why can't this be detected afterwards

Because there is no difference between the Integer with value 10 that was autoboxed and another Integer with value 10

How can I get around this

You need to add separate methods to overload for primitive values, these can handle the primitive values, so they do not get autoboxed.

Compare an Object to a primitive type

Step 1 :
Check field.isPrimitive(). If it returns true then it's a primitive type. and proceed to step 3.

Step 2:
If it's not primitive then you can directly check
field.getType() == newValue.getClass() and then set the value

Step 3:
if it's primitive then you need to have a static map

public final static Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>();
static {
map.put(boolean.class, Boolean.class);
map.put(byte.class, Byte.class);
map.put(short.class, Short.class);
map.put(char.class, Character.class);
map.put(int.class, Integer.class);
map.put(long.class, Long.class);
map.put(float.class, Float.class);
map.put(double.class, Double.class);
}

Class<?> clazz = map.get(field.getType());
then check clazz == newValue.getClass() and then set the variable.

How to determine the primitive type of a primitive variable?

Try the following:

int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());

It will print:

java.lang.Integer
java.lang.Float

As for instanceof, you could use its dynamic counterpart Class#isInstance:

Integer.class.isInstance(20);  // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false

Check if input is of Primitive type in Java?

Before I address your question, you appear to have a number of misconceptions about Java and Scanner.

  1. The stuff you read from the input stream is characters or bytes. Those characters or bytes can be interpreted as representing many things ... but it is a matter of interpretation. Furthermore the same sequence of characters could mean different things ... depending on how you choose to interpret them; e.g. "12345" could easily be interpreted as a string, an integer or a floating point number. And if you map that to Java types, then that could be String, short, int, long, float or double ... and many more besides.

    The point is ... you (the programmer) have to tell the parser (e.g. Scanner) what to expect. You can't expect it to guess (correctly).

  2. Assuming that you had managed to read as reference or (true) primitive types, you would not be able to assign them to the same variable. Integer etcetera are NOT primitive types!

  3. The Scanner.readLine() method reads and returns the rest of the current line as a String. It makes no attempt to interpret it. The Java type of the result is String ... and nothing else.


So how should you implement it. Well here's a sketch of a crude version:

     String input = br.readLine();
showPrimitive(input); // Note spelling!

public void showPrimitive(String input) {
if (input.equalsIgnoreCase("true") ||
input.equalsIgnoreCase("false")) {
System.out.println("Primitive : boolean");
return;
}
try {
long num = Long.parseLong(input);
if (num >= Byte.MIN_VALUE &&
num <= Byte.MAX_VALUE) {
System.out.println("Primitive : byte");
} else if (num >= Short.MIN_VALUE &&
num <= Short.MAX_VALUE) {
System.out.println("Primitive : short");
} else if (num >= Integer.MIN_VALUE &&
num <= Integer.MAX_VALUE) {
System.out.println("Primitive : int");
} else {
System.out.println("Primitive : long");
}
return;
} catch (NumberFormatException ex) {
// continue
}
// deal with floating point (c.f. above)
// deal with char: input length == 1
// anything else is a String.
}

Note that the above entails using exceptions in a way that a lot of people would object to. However, doing a better job is tricky ... if you are going to support all possible values of each of the primitive types.

But I would return to a point I made earlier. If you look at the code above, it is making hard-wired choices about how to interpret the input. But how do you know if you are making the right choices? Answer: you have to specify how the input parsing should behave ... not rely on something else to give you the "right" answer by magic.

Check type of primitive field

You're using the wrong constant to check for Long primitives - use Long.TYPE, each other primitive type can be found with a similarly named constant on the wrapper. eg: Byte.TYPE, Character.TYPE, etc.



Related Topics



Leave a reply



Submit