How to Determine the Primitive Type of a Primitive 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

how to get primitive type from object in Java?

What you are describing are primitive types, not classes. You can do it like this.

class Foo {
public int x;
public char y;
}

Foo foo = new Foo();
Field[] fields = foo.getClass().getDeclaredFields();
for (Field f : fields) {
System.out.println(f.getAnnotatedType() + " " + f.getName());
}

prints

int x
char y

If you just want to have a getter to return a value of a primitive field you can do this in your class.

int someVal = 10;
public int getSomeVal() {
return someVal;
}

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

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.



Related Topics



Leave a reply



Submit