Creating a Method for multiple object types in Java
I'm a fairly new to Java and to programming, so excuse me if this is a stupid question.
I want to create a method exceptionchecker
that does this
public void exceptionchecker(Object check){
if(check.size() == 0 && some_other_stuff) throw new IllegalArgumentException();
}
The problem is that the object passed might be a list or a string. So depending on the case I need to either use .length
or .size()
.
Is there any easy way to do this, or am I better off creating two sep开发者_开发技巧erate methods?
EDIT: If it's relevant, the list would be of type String as well.
You could use instanceof
to do some checks, and it is reliable, but it doesn't leave it self as open to extension, or clarity.
The reason for this is
- If you're checking something other than a list or a String, you should know about it at compile time
- As you add more checks, it's going to cause a giant check method that will get tough to maintain.
Using two methods is most appropriate.
public void exceptionCheck(String s) {
if(s.length() == 0) throw new IllegalArgumentException();
}
public void exceptionCheck(List<?> l) {
if(s.isEmpty()) throw new IllegalArgumentException();
}
You could use check.class() to tests if the object is a string or list and cast it, but the more elegant method would be implementing an exception checker for every type you need
void exceptionChecker( String check ) {
...
}
void exceptionChecker( List check ) {
...
}
void exceptionChecker( Object check ) {
...
}
Instead of passing an Object, consider passing in a wrapper object over the relevant type (String, List, Map etc.); for e.g. ExceptionData which honors the contract of implementing the isEmpty
method. This exception data would have subclasses which override the isEmpty
method when required.
Sure, this might result in a few more classes being created plus a few objects created at runtime, but unless you are dealing with a million such entities, this seems to be a far cleaner/explicit approach.
If this level of verboseness is not acceptable, consider method overloading to do your bidding which results in cleaner client code plus no creation of extra objects.
Having two signatures works if you know the type of the object at compile-time. At run-time, you can use instanceof to determine the type.
if (check instanceof Foo) {
Foo foo = (Foo) check;
if (foo.bar() == something) { ... }
}
You might want to first check if the Object is of the type your method can handle using instanceof
operator.
I'd recommend just using something like Guava and its Preconditions class to do this sort of thing. Using static imports, you'd do something like:
checkArgument(something.size() > 0 || someOtherStuff);
It's easy enough to just put whatever checks there. In other words, just use a method that takes a boolean
argument and do the actual checks outside the method.
精彩评论