Comment “dynamique” cast une instance du type d'Objet dans son type de données spécifique?

public Object foo(int opt){
  if (opt == 0) return new String();
  else if (opt == 1) return new Integer(1);
  else if (opt == 2) return new Double(1);
  else if ...
  .. and many more
}

public void doSomething(String s){..}
public void doSomething(Integer i){..}
public void doSomething(Double d){..}
... and many more doSomething method

public static void main(String[] args){
  ...
  Object o = foo(x); //x is a value obtained during runtime, e.g. from user input

  //now I want to call doSomething method
  //(1)
  if (o instanceof String) doSomething((String) o);
  else if (o instanceof Integer) doSomething((Integer) o);
  else if (o instanceof Double) doSomething((Double) o);
  ...
  //(2)
}

Est-il une meilleure façon de simplifier les déclarations incluses par (1) ... (2)?
Java Réflexion aider?

OriginalL'auteur Pahlevi Fikri Auliya | 2011-04-11