java - Method nonvisibility of same instanceof but differing class -


i have below:

item var; 

depending on user input, initialized different class:

if (/*user input*/ == 1) {     var = new item(); } else {     var = new truck(); } 

the classes defined as:

public class truck extends item {     public void somemethod();     public void exclusivemethod(); } public class item {     public void somemethod(); } 

note truck has exclusive method, exclusivemethod() item not have. depending on conditions, series of methods called on var:

// return true if var initialized truck if (/*conditions*/) {     var.somemethod();     var.exclusivemethod(); } else {     var.somemethod(); } 

netbeans pops error exclusivemethod() cannot found because not in item. need method visibility of exclusivemethod() when var initialized truck. have constraints, though: item var; must in code before other logic, , cannot create interface implement in both item , truck. cannot modify public class item{} @ all.

what can do?

you can use reflection apis call exclusivemethod .

the code -

method m = var.getclass().getmethod("exclusivemethod", null); if(m != null) {     m.invoke(var, null); } 

you can more information relfection apis here - http://docs.oracle.com/javase/tutorial/reflect/index.html


another way casting var onto truck , if sure var object of type truck . example code -

if(var instanceof truck) {     ((truck)var).exclusivemethod() } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -