Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable to any type and check type of this in Java?

I have serious problems when implementing a java library for use in Android. I need global variables, I've solved this by applying Singleton.

But now I need to use variables without specifying the type. As a solution I found using Object o.

Object o, how I check the type of o?

o.isArray () // Ok is type Array

But to know if it is int, double, ...?

Another solution to using Object or variable of any type?

For example:

public String arrayToString (Object o) {
    if (o.getClass (). isArray ()) {
        Arrays.toString return ((Object []) o);
        Else {}
        o.toString return ();
    }
}

Object [] a = (Object []) LIB.getConf ("test");
a_edit [0] = "new value";
a_edit [1] = 2013;

x.arrayToString ("test") / / return test
x.arrayToString (1989) / / return 1989
x.arrayToString (a) / / return [new value, 2013]

thanks you,

like image 789
ephramd Avatar asked Oct 19 '25 02:10

ephramd


1 Answers

Use the instanceof operator.

For example:

if (o instanceof Integer) {
   //do something
} else if (o instanceof String) {
   //do something else
} else if (o instanceof Object[]) {
   //or do some other thing
} else if (o instanceof SomeCustomObject) {
   //....
}
like image 101
Konstantin Yovkov Avatar answered Oct 21 '25 17:10

Konstantin Yovkov