I have something like the below:
Item var;
Depending on user input, it will be initialized as a different class:
if (/*user input*/ == 1) {
var = new Item();
} else {
var = new Truck();
}
The classes are defined as:
public class Truck extends Item {
public void someMethod();
public void exclusiveMethod();
}
public class Item {
public void someMethod();
}
Note Truck
has an exclusive method, exclusiveMethod()
that Item
does not have. Depending on some conditions, a series of methods will be called on var
:
// will only return true if var was initialized as Truck
if (/*conditions*/) {
var.someMethod();
var.exclusiveMethod();
} else {
var.someMethod();
}
Netbeans pops up an error that exclusiveMethod()
cannot be found because it is not in Item
. I need method visibility of exclusiveMethod()
only when var
was initialized as Truck
. I have some constraints, though: Item var;
must be in my code before other logic, and I cannot create an interface which I then implement in both Item
and Truck
. I also cannot modify public class Item{}
at all.
What can I do?
You can use reflection APIs to call the
exclusiveMethod
.The code would look something like -
You can get more information about relfection APIs here - http://docs.oracle.com/javase/tutorial/reflect/index.html
Another way to get this is by casting the
var
onto aTruck
, if you are sure that var is an object of typeTruck
. the example code for that would be -