简体   繁体   中英

passing Integer or String array as an argument in java

I am writing a java function which which takes two argument : one is a string type and other could be an array of String, Integer, Float, Double, Boolean or just a String .

In JavaScript it is quite easy to pass any data as an argument, but what are the good solutions in java ?

In java you can only pass the data defined in by the method. A way around this can be to use Object as an argument. Besides that you can create many methods with the same name, but accepting different arguments. Example:

public void example(String str, Object obj){ /* code */ }

When using Object you need to make sure to check what type it is, so you don't end up trying to use an integer as a string array.

I am quite sure that using Object is not the best way to go and you should use multiple methods with different arguments.

You can overload the method to accept different parameters.

 void doSomething(String x, int[] y) {}

 void doSomething(String x, String[] y) {}

 void doSomething(String x, String y) {}

That way, you still have type-safety (which an Object argument does not give you).

I suppose this is what you want

public void method1(String str, Object ...val)

Inside the method body, you will have to handle different objects accordingly

As you want second object as any data type array you can do something like this

public void _methodName(String arg1,Object[] arg2)

As String,Integer,Float,Boolean all are inherited from java.lang.Object ,you can simply pass Object[] as second argument and you pass argument( String,Int,....etc ) whatever you want.

The prototype of method as per your need is as follows :

public void testMethod(String strVal, Object[] genericVal)

Now in the body part you have to cast the object into the required format by Using Wrapper Classes.

Above implementation will resolve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM