Javaman
Javaman

Reputation: 29

How to have a method have different input types java

I have a program on my computer that simulates a server on the internet and the fake server needs to be able to send multiple data types to some classes. Like for instance at one point of the program the server needs to send an int to a class then convert that int to a string and send it to another.

Basically what I am asking is if a method can have multiple data types for an input(Does this make sense? if not ill try to explain better). Is there any way to do this without creating many different methods?

Edit: Also is there a way to tell the difference between the types passed in (to prevent errors)

Upvotes: 2

Views: 11347

Answers (5)

Jord Sonneveld
Jord Sonneveld

Reputation: 456

You could use the "hashed adapter" pattern.

Public interface Adapter {
  Public void handle(object o);
}

Public class StringAdapter implements Adapter {
  Public void handle(String st) { // stuff ...
}

Public class IntegerAdapter implements Adapter {
  Public void handle(Integer intgr) { // stuff ...
}

Private static final Map adapters = new HashMap();
Adapters.put(string.class, new stringAdapter());
Adapters.put(Integer.class, new IntegerAdapter());

Public void handleMe(Object o) {
  Adapters.get(o.getClass()).handle(o);
}

Ive always liked this more than the ol' cascade of ifs and else's.

On my iPad so sorry about formatting and terseness and speellling.

Upvotes: 0

HRgiger
HRgiger

Reputation: 2790

Well I have also wondered and wrote below block. I think instanceof better but I tried getclass.

public static void main(String[] args){

    System.out.println(method("This is a test"));
}


private static String method(Object o){
            System.out.println(o.toString());
    String status = "";
    String className;
    String[] oList = {"Double","Integer","String","Double","Float","Byte","Short","Long","Character","Boolean" };

    for(int i = 0;i<oList.length;i++){

        className = "java.lang." + oList[i];
        Class testClass;
        try {
            testClass = Class.forName(className);
            if(o.getClass().equals(testClass)){

                status =  "Your object is " + oList[i];


            }
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }

    }


    return status;

} 

Upvotes: 0

Karel-Jan Misseghers
Karel-Jan Misseghers

Reputation: 807

What you want are Generic methods or classes. to check what type an object is you'll have to use the 'instanceof' method

you can either make an entire class generic or just a single method, an example of a generic class:

package javahowto;
public class Member<T> {
 private T id;
 public Member(T id) {
   this.id = id;
 }
 public T getId() {
   return id;
 }
 public void setId(T id) {
   this.id = id;
 }
 public static void main(String[] args) {
   Member<String> mString = new Member<String>("id1");
   mString.setId("id2");
   System.out.printf("id after setting id: %s%n", mString.getId());
   //output:  id after setting id: id2

   Member<Integer> mInteger = new Member<Integer>(1);
   mInteger.setId(2);
   System.out.printf("id after setting id: %d%n", mInteger.getId());
   //output:  id after setting id: 2
 }

Now you now what to look for I'm sure you'll find the best solution to your problem.

check out: http://download.oracle.com/javase/tutorial/java/generics/index.html http://en.wikipedia.org/wiki/Generics_in_Java

...

Upvotes: 0

Ryan Amos
Ryan Amos

Reputation: 5452

If I understand correctly, you're asking if a method foo() can have multiple different inputs for its parameters

That way foo(Integer i) and foo(String s) are encased in the same method.

The answer: yes, but it's not pretty

foo(Object o)

Is your method declaration

Now you need to sort out the different types of possibilities

if(o instanceof Integer){
    stuff();
} else if (o instanceof String){
    moreStuff();
}

Just chain those else/if statements for the desired result.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can have a method which takes Object which is any type. In Java 5.0 and later primitives will be auto-boxed and passed as an object as well.

void method(Object o);

can be called using

method(1);
method("hello world");
method(new MyClass());
method(null);

Upvotes: 4

Related Questions