java - Return different type of data as per the condition -
i have problem in if in method, called rest end point, have errorlog method should return file. otherwise, if correct, should return json.
is there way change return type of method per condition?
i start saying wrong approach problem. correct approach throw exception if have error, , deal using exception handler. alternatively, use call-back handle error case before returning method. (that deal "generate errorlog" use-case.)
having said ....
here's "complex" object can use return 1 of 2 types:
public class aorb { private final a; private final b b; private final boolean isa; public aorb(a a) { this.a = a; this.b = null; isa = true; } public aorb(b b) { this.a = null; this.b = b; isa = false; } public boolean isa() { return isa; } public geta() { if (isa) { return a; } else { throw illegalstateexception("not a!") } } public b getb() { if (!isa) { return b; } else { throw illegalstateexception("not b!") } } }
alternatively, declare return type object
, use type casting , instanceof
in calling method discriminate returned values.
Comments
Post a Comment