Here is a very simple case: I am trying to cast an Object type to a primitive like this:
Object object = Integer.valueOf(1234);
int result1 = int.class.cast(object); //throws ClassCastException: Cannot convert java.lang.integer to int
int result2 = (int)object; //works fine
This is the source code of cast method of class 'Class'
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
private String cannotCastMsg(Object obj) {
return "Cannot cast " + obj.getClass().getName() + " to " + getName();
}
Why is this happening? Same is happening with other primitives too.
Live Example
cast can't really work well for primitives, given that it can't return a value of the actual primitive type, due to generics in Java... so it would end up boxing again anyway. And if you're not assigning straight to an int value, it would have to be boxed for that reason too.
So basically, if you want to convert to int, just cast directly.
isInstance is documented to always return false for primitives:
If this Class object represents a primitive type, this method returns false.
... cast probably should be too.
Here is a table of primitive types and their equivalent wrapper class.
Primitive type Wrapper class
============== =============
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
I would like to create a method that would convert any given primitive variable into an appropriate class. I have tried something like below, but that obviously does not work. Any help would be appreciated:
public static <T> T forceBox(T t) {
switch (T) {
case boolean.class : return new Boolean(t);
case int.class : return new Integer(t);
// etc
}
}
the caller code looks like:
int x = 3;
System.out.println("x wrapper type: " + forceBox(x).getClass());
Though this is completely unnecessary in most cases, just use
public static <T> T forceBox(T t) { // compiler will add the conversion at the call site
return t;
}
Though you can also just use
Object o = <some primitive>;
The conversion is already done when needed as part of the boxing process.
For example, there needs to be a written a generic program for addition. It needs to be intelligent in a way that it determines the type of arguments passed to it and then output the answer in the same type.
For more elaboration:
If I want to write only one method to add two numbers ( of any type
like int, float, double etc), what should I do that the method itself
determines the type of number passed and returns the calculated sum in
the same type?
Is there any way to sort this out? Any help would be highly appreciated!
Code view: For example arguments passed are 5 & 6 i.e. integers.
addition(5,6);
Now, what I want is a function add that somehow determines the type (i.e. integer in this case) & returns the result. Like:
public (determined return type) add((determined returned type) space variable, (determined returned type) space variable){
return result;
}
This should work:
public static <T extends Number> T addition(T a, T b) {
if (a instanceof Integer)
return (T) (Object) (a.intValue() + b.intValue());
// + similar code for all primitive types and possibly also BigInteger and BigDecimal
}
You could have a method declared:
public <N extends Number> N add(N n1, N n2)
This would require instanceof checks to actually implement and return the desired type.
More complex answer.
#SuppressWarnings("unchecked")
public <T extends Number> T addition (T argA, T argb)
{
if(argA instanceof Integer)
{
return (T)new Integer ((Integer)argA + (Integer)argb);
}
else if (argA instanceof Double)
{
return (T)new Double((Double)argA + (Double)argb);
}
//..
}
I have a method in my test framework that creates an instance of a class, depending on the parameters passed in:
public void test(Object... constructorArgs) throws Exception {
Constructor<T> con;
if (constructorArgs.length > 0) {
Class<?>[] parameterTypes = new Class<?>[constructorArgs.length];
for (int i = 0; i < constructorArgs.length; i++) {
parameterTypes[i] = constructorArgs[i].getClass();
}
con = clazz.getConstructor(parameterTypes);
} else {
con = clazz.getConstructor();
}
}
The problem is, this doesn't work if the constructor has primitive types, as follows:
public Range(String name, int lowerBound, int upperBound) { ... }
.test("a", 1, 3);
Results in:
java.lang.NoSuchMethodException: Range.<init>(java.lang.String, java.lang.Integer, java.lang.Integer)
The primitive ints are auto-boxed in to object versions, but how do I get them back for calling the constructor?
Use Integer.TYPE instead of Integer.class.
As per the Javadocs, this is "The Class instance representing the primitive type int."
You can also use int.class. It's a shortcut for Integer.TYPE. Not only classes, even for primitive types you can say type.class in Java.
To reference primitive types use, for example:
Integer.TYPE;
You will need to know which arguments passed into your method are primitive values. You can do this with:
object.getClass().isPrimitive()
Since the primitive types are autoboxed, the getConstructor(java.lang.Class<?>... parameterTypes) call will fail. You will need to manually loop through the available constructors. If all types match then you're fine. If some types do not match, but the required type is a primitive AND the available type is the corresponding wrapper class, then you can use that constructor. See bellow:
static <C> Constructor<C> getAppropriateConstructor(Class<C> c, Object[] initArgs){
if(initArgs == null)
initArgs = new Object[0];
for(Constructor con : c.getDeclaredConstructors()){
Class[] types = con.getParameterTypes();
if(types.length!=initArgs.length)
continue;
boolean match = true;
for(int i = 0; i < types.length; i++){
Class need = types[i], got = initArgs[i].getClass();
if(!need.isAssignableFrom(got)){
if(need.isPrimitive()){
match = (int.class.equals(need) && Integer.class.equals(got))
|| (long.class.equals(need) && Long.class.equals(got))
|| (char.class.equals(need) && Character.class.equals(got))
|| (short.class.equals(need) && Short.class.equals(got))
|| (boolean.class.equals(need) && Boolean.class.equals(got))
|| (byte.class.equals(need) && Byte.class.equals(got));
}else{
match = false;
}
}
if(!match)
break;
}
if(match)
return con;
}
throw new IllegalArgumentException("Cannot find an appropriate constructor for class " + c + " and arguments " + Arrays.toString(initArgs));
}
you can write
int[].class.getComponentType()
or
Integer.TYPE
or
int.class
If primitive int value is autoboxed into Integer object, it's not primitive anymore. You can't tell from Integer instance whether it was int at some point.
I would suggest passing two arrays into test method: one with types and another with values. It'll also remove ambiguity if you have a constructor MyClass(Object) and pass string value (getConstructor would be looking for String constructor).
Also, you can't tell expected parameter type if parameter value is null.
To actually check if a type is a primitive or it's wrapper use:
ClassUtils.isPrimitiveOrWrapper(memberClazz)
In the case you want to check if it's a specific type take a look at this:
https://stackoverflow.com/a/27400967/2739334
In any case #Andrzej Doyle was completely right!
How can I check to make sure my variable is an int, array, double, etc...?
Edit: For example, how can I check that a variable is an array? Is there some function to do this?
Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).
The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:
int x;
You can be sure it will only ever hold int values.
If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.
If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:
List y;
...
if (y instanceof ArrayList) {
...its and ArrayList...
}
However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.
Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.
Example:
class Typetester {
void printType(byte x) {
System.out.println(x + " is an byte");
}
void printType(int x) {
System.out.println(x + " is an int");
}
void printType(float x) {
System.out.println(x + " is an float");
}
void printType(double x) {
System.out.println(x + " is an double");
}
void printType(char x) {
System.out.println(x + " is an char");
}
}
then:
Typetester t = new Typetester();
t.printType( yourVariable );
a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.
boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class.
Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.
I took this information from:
How do you know a variable type in java?
This can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.
By the way, this is known as Reflection. Here's some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/
Just use:
.getClass().getSimpleName();
Example:
StringBuilder randSB = new StringBuilder("just a String");
System.out.println(randSB.getClass().getSimpleName());
Output:
StringBuilder
You may work with Integer instead of int, Double instead of double, etc. (such classes exists for all primitive types).
Then you may use the operator instanceof, like if(var instanceof Integer){...}
Well, I think checking the type of variable can be done this way.
public <T extends Object> void checkType(T object) {
if (object instanceof Integer)
System.out.println("Integer ");
else if(object instanceof Double)
System.out.println("Double ");
else if(object instanceof Float)
System.out.println("Float : ");
else if(object instanceof List)
System.out.println("List! ");
else if(object instanceof Set)
System.out.println("Set! ");
}
This way you need not have multiple overloaded methods. I think it is good practice to use collections over arrays due to the added benefits. Having said that, I do not know how to check for an array type. Maybe someone can improve this solution. Hope this helps!
P.S Yes, I know that this doesn't check for primitives as well.
The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.
Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case object.getClass().isArray() will tell you.
I did it using: if(x.getClass() == MyClass.class){...}
I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.
//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);
// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);
// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);
Here is a method:
public static void checkClass (Object obj) {
Class cls = obj.getClass();
System.out.println("The type of the object is: " + cls.getSimpleName());
}
Basically , For example :
public class Kerem
{
public static void main(String[] args)
{
short x = 10;
short y = 3;
Object o = y;
System.out.println(o.getClass()); // java.lang.Short
}
}
None of these answers work if the variable is an uninitialized generic type
And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:
<T> T MyMethod(...){ if(T.class == MyClass.class){...}}
Is NOT valid because you cannot pull the type out of the T parameter directly, since it is erased at runtime time.
<T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}
This works because the caller is responsible to instantiating the variable out before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this
I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T is a kind of variable), I feel it should be included
var.getClass().getSimpleName()
Let's take a example
String[] anArrayOfStrings = { "Agra", "Mysore", "Chandigarh", "Bhopal" };
List<String> strList = Arrays.asList(anArrayOfStrings);
anArrayOfStrings.getClass().getSimpleName() //res => String[]
strList.getClass().getSimpleName() // res => ArrayList
You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.
reference - Here is the Oracle docs link
I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.
public class TypeTester <T extends Number>{
<T extends Object> String tester(T ToTest){
if (ToTest instanceof Integer) return ("Integer");
else if(ToTest instanceof Double) return ("Double");
else if(ToTest instanceof Float) return ("Float");
else if(ToTest instanceof String) return ("String");
else if(ToTest.getClass().isArray()) return ("Array");
else return ("Unsure");
}
}
I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.
public class Generics {
public static void main(String[] args) {
int [] myArray = new int [10];
TypeTester<Integer> callFunction = new TypeTester<Integer>();
System.out.println(callFunction.tester(myArray));
}
}
You can swap out the myArray in the final line for say 10.2F to test Float etc
public static void chkType(Object var){
String type = var.getClass().toString();
System.out.println(type.substring(16));
//assertEquals(type,"class java.lang.Boolean");
//assertEquals(type,"class java.lang.Character");
//assertEquals(type,"class java.lang.Integer");
//assertEquals(type,"class java.lang.Double");
}
A simple solution I found was the following rather than wondering about fire command. Also, you can check this article
public class DataTypeCheck
{
public static void main(String[] args)
{
String jobTitle = "Agent";
int employeeId = 7;
double floating= 10.0;
String bond = jobTitle + employeeId;
System.out.println(((Object)floating).getClass().getSimpleName());
System.out.println(((Object)employeeId).getClass().getSimpleName());
System.out.println(((Object)jobTitle).getClass().getSimpleName());
System.out.println(((Object)bond).getClass().getSimpleName());
}
}
Output:
Double
Integer
String
String