Java 等价于 C# 动态类类型? [英] Java equivalent to C# dynamic class type?

查看:19
本文介绍了Java 等价于 C# 动态类类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 c# 的世界.

I'm coming from the world of c#.

在 C# 中,我可以使用动态类 http://msdn.microsoft.com/en-us/library/dd264741.aspx

in C# i am able to use the class dynamic http://msdn.microsoft.com/en-us/library/dd264741.aspx

这让我不必使用模板化/泛型类,但可以在特定情况下获得类似的感觉.

This allows me to not have to use templated/generic classes but achieve a simliar feel for certian situations.

我在 Internet 搜索中一直没有成功,因为不幸的是,dynamic"和java"关键字出现了很多与动态架构无关的信息.

I'm have been unsuccessfull in internet searchs as unfortunately 'dynamic' and 'java' keywords turn up alot of unrelated infromation on dynamic architectures.

我在 javaFX 中有所涉猎,并且有一个类型 var 似乎与 c# 的动态具有相同的用法.但是它似乎不能在 Java 中使用.

I have dabbled a bit in javaFX and there is a type var which appears to have the same usage as c#'s dynamic. However it doesnt appear to be usable in Java.

谢谢,斯蒂芬妮

推荐答案

Java 不支持动态类型,但您可以在 Java 中使用动态代理模拟类似的东西.首先,您需要声明一个接口,其中包含要在对象上调用的操作:

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();
}

然后在 myObjectInstance 上创建用于动态调用的代理:

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();

MyHandler 声明如下:

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);
  }
}

所以,如果 myObject 有方法 foo() 和 boo(),它们将被调用,否则,你会得到一个 RuntimeException.

so, if myObject has methods foo() and boo(), they will be invoked, or else, you'll get a RuntimeException.

还有许多可以在 JVM 中运行的语言支持动态类型,例如Scala、Groovy、JRuby、BeanShell、JavaScript/Rhino 等等.Java 7 对 JVM 进行了一些更改以支持本机动态调度,因此这些语言可以执行得更好,但此类功能不会直接在静态类型的 Java 语言中公开.

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.

这篇关于Java 等价于 C# 动态类类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆