Java doesn't support dynamic typing, but you can simulate something like that using dynamic proxy in Java. First you'll need to declare an interface with operations you want to invoke on your objects:
public interface MyOps {
void foo();
void boo();
}
Then create Proxy for dynamic invocation on myObjectInstance:
MyOps p = (MyOps) Proxy.newProxyInstance(getClass().getClassLoader(), //
new Class<?>[] { MyOps.class }, //
new MyHandler(myObject));
p.foo();
p.boo();
where MyHandler is declared like this:
public class MyHandler implements InvocationHandler {
private final Object o;
public MyHandler(Object o) {
this.o = o;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Method method = o.getClass().getMethod(m.getName(), m.getParameterTypes());
return method.invoke(o, args);
}
}
so, if myObject has methods foo() and boo(), they will be invoked, or else, you'll get a RuntimeException.
There is also number of languages that can run in JVM support dynamic typing, e.g. Scala, Groovy, JRuby, BeanShell, JavaScript/Rhino and many others. There is some JVM changes are coming in Java 7 to support a native dynamic dispatch, so these languages could perform much better, but such feature won't be directly exposed in statically typed Java language.