java


Methods, Optional Parameters and/or Accepting multiple Data Types


After browsing the web for a while looking for an answer to my question I can't find any posts which seem to offer an effective solution to my issue.
Currently I would overload a method for each different data type input.
For example:
public void ex1(String in){
public void ex1(int in){
I would imagine there would be a way to condense this into one line
public void ex1(opt(String in), opt(int in)){
or
public void ex1((String/int) in){
However, as far as I've seen, nobody has presented a reasonable method to use either of these forms.
Overloading does work, but doesn't look as clean as I might like it, so any workarounds or ideas would be appreciated.
There is a way, but you acn only provide one optional parameter.
That way is to use ... in front of parameter type.
For ex:
public void ex1(int someint, String... in)){
In this case String in is an optional parameter which you can provide or not. But int someint is a must provide parameter.
So String... in is basically a String[] in. Since array can be null.... Other than this (atleast I) dont know of any other way to achieve this.
This means you also cant do something like one of the parameters has to be entered and other can be ignored. You can ignore just one parameter and other has to be passed.
Also this works with just one parameter per method. In other words, just one parameter can be made optional. Else you must use method overloading.
However (as said in comments), this is not an effective way. Since you will have to write logic for each varaible's possibility and the code would be a great mess, compared to the sweet and effective way by method overloading.
EDIT:
varargs (or this optional parameter) must appear as the last parameter in method. Thanks #Makoto for pointing this out.
I would imagine there would be a way to condense this into one line
You could probably do something like this:
public void ex1(String in1, int in2) { // I don't believe they can have the same name
// ...
}
As far as an optional variables, I would just set the variables to a value, and inside the method, test to see if that value is equal to that "default" value.
ex1("Hey", 0);
public void ex1(String in1, int in2) {
boolean useString = true;
boolean useInt = true;
if(in1.length() < 1) {
useString = false;
}
if(in2 != 0) {
useInt = false;
}
if(useString) {
// ...
}
if(useInt) {
// ...
}
}
EDIT: For one optional variable, see Jaskaranbir Singh's answer.
Try this:
public void ex1(Serializable in){
// .....
}
Always works for me. String is Serializable, and for primitive types it use autoboxing and convert automatically int to Integer and so on, and Integer is also Serializable, so ex1(1) will work as expexted. All you need is detect real type:
if(Integer.class.isInstance(in)){
int intVal = ((Integer)in).intValue();
// ...
} else if(String.class.isInstance(in)){
String strVal = (String) in;
// ...
}
Corner case is when in is null, - in that case its hard to detect real type(still possible), but most of all you dont need that.
what I would do is this:
public void ex1(String[] args){}
by using this you can have as many data types as you want, if any.
The full code would look something like this:
public void ex1(String[] args){
try{
if(/*I know there is some parse string techique*/args[] == ...){
//code here
}
catch(Exception E){}
hopefully you get the idea, basically you have an array of string an parse it into an int, boolean, ect...and put the code that you would put in the separate functions into the if statements

Related Links

Why is arbitrary precision in double literals allowed in Java?
How to call an ActiveX method through java when control doesn't allow automation (com4j/jacob)?
android - SimpleAdapter + SectionIndexer
How to optimize for-comprehensions and loops in Scala?
Control Android Media Player
HTML Page not Showing up in Java Swing JTextPane
Problem inserting into an SQL Server Database with Java
count number of distinct words
How to make REST call to JBOSS issue tracker
log4j, nested diagnostic contexts
Cannot access wsdlURL - using Netbeans 7.0
Jar got copied twice while creating war file from ANT
Log4j: Log File correct, but Stdout only showing a subset
Easiest way to submit a form to ServletUnit using something like WebRequest in HttpUnit
JPA/Hibernate mapping error when entities are located in multiple JAR files
Is The Java Tutorials Translucent Window example giving trouble to those playing with jdk7?

Categories

HOME
coq
netbeans
stock
office365api
disassembler
opengl-es-2.0
add
amazon-cloudformation
primary-key
google-translate
maude-system
zebra-printers
iron-router
dynamics-crm-online
vaadin7
pc
reactive-cocoa
sms-gateway
nhibernate-envers
conemu
sylius
telerik-reporting
cas
fifo
gsmcomm
binary-data
titanium-mobile
column-family
xmlreader
atl
vxworks
restlet
hot-module-replacement
hockeyapp
event-driven
lumberjack
jvm-languages
android-mediaprojection
keydown
gpx
businessworks
cubic-spline
google-datalayer
avconv
flickr-api
dotcover
appcompat
python-c-api
paxos
diagnostics
lift-json
zendesk-app
flow-control
flutterwave
spring-cache
smart-table
objective-c-swift-bridge
google-feed-api
rotativa
bonobo
pcf
xml-attribute
mongocsharpdriver
plottable.js
fputcsv
clang-static-analyzer
holder.js
php-parse-error
ios4
two-factor-authentication
netmq
eclipse-clp
metaclass
simple-framework
wireshark-dissector
fouc
ios9.1
lustre
block-device
operator-precedence
typekit
mdt
wordpress-theme-customize
client-side-templating
openexr
reactfx
concurrent-collections
stxxl
oam
farseer
tws
xamlparseexception
flashvars
clipper
rdoc
automount
netbeans-6.9
spyware
django-tagging
xdomainrequest
servicehost
iphone-web-app
xfbml
dbal
mirah
vc90
virtual-functions
uimenucontroller
phonon
msdev
wsdl.exe

Resources

Encrypt Message