你能在GWT客户端使用Java Reflection api吗?
是否可以在GWT客户端使用javareflectionAPI? 我想使用reflection来查找Javabean上的属性值。 这可能吗?
我一直在那里,解决方案确实是使用延迟绑定和生成器。 您可以在此处看到使用Generators来克服GWT客户端中缺少Reflection的问题:
http://jpereira.eu/2011/01/30/wheres-my-java-reflection/
希望能帮助到你。
您可以使用GWT Generatorsfunction,该function允许您在GWT编译阶段生成代码。
您想要内省的bean可以扩展一个具有定义方法的类
public Object getProperty(String propertyName){}
我们将这个类称为IntrospectionBean
。
假设您将bean定义为:
public class MyBean extends IntrospectionBean { private String prop1; private String prop2; }
GWT生成器可以访问MyBean的所有字段,并且在迭代MyBean的所有字段之后,它可以在GWT编译期间生成getProperty(String propertyName)
方法。
生成的类可能如下所示:
public class MyBean extends IntrospectionBean { private String prop1; private String prop2; public Object getProperty(String propertyName) { if ("propr1".equals(propertyName)) { return prop1; } if ("propr2".equals(propertyName)) { return prop2; } return null; } }
您可以简单地使用myBean.getProperty("prop1")
,以便在运行时根据它的名称检索属性。
在这里,您可以找到如何实现gwt生成器的示例
由于GWT代码被转换为Javascript,因此不支持直接使用reflectionAPI。
有一个小项目GWT-Reflection ,允许在GWT中使用reflection。
GWT不完全支持reflection,你可以看到以下链接:
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsCompatibility.html
你应该注意java和javascript之间的边界。 在GWT中,所有代码都编译为javascript,因此您必须检查JavaScript是否是一个明确定义的reflection。
我公开了我的gwt-reflection库。
https://github.com/WeTheInternet/xapi/tree/master/gwt/gwt-reflect https://github.com/WeTheInternet/gwt-sandbox/tree/xapi-gwt/user/src/com/google/gwt /反映
由于类路径问题试图让Gwt选择我自己的Class.java版本,我最后只是分叉Gwt,添加了java 8和reflection支持,现在维护net.wetheinter:gwt – *:2.7.0这有这个支持烘焙(我将在Gwt 2.8上线后的一段时间内发布2.8)
它支持三个级别的reflection:
整体:
// Embeds all data needed to perform reflection into hidden fields of class GwtReflect.magicClass(SomeClass.class); SomeClass.getField(fieldName).set(null, 1);
轻量级:
// Allows direct reflection, provided ALL parameters are literals, or traced to literals SomeClass.class.getField("FIELD_NAME").set(null, 1);
飞锤:
// Skips creating a Field object entirely, and just invokes the accessor you want // All params must be literals here as well GwtReflect.set(SomeClass.class, "FIELD_NAME", null, 1);
这些示例也适用于方法和构造函数。 对注释有基本的支持,未来还会有更多支持。
如果您只想使用reflection来获取私有字段,请考虑使用jsni(javascript本机接口); 它没有私人或公共的概念,所以你可以抓住你想要的任何东西:
package com.foo; class SomeClass { private String someField; private static int someInt; } //accessors: native String ripField(SomeClass from) /*-{ return from.@com.foo.SomeClass::someField; }-*/; native int ripInt() /*-{ return @com.foo.SomeClass::someInt; }-*/;
此外,我正在完成java.lang.Class
newInstance
/ reflection的仿真。
如果您想玩它,我会在大约两天内回复此链接。
它要求您通过我路由到自定义生成器的方法传递类(如GWT.create
,除了它返回生成的java.lang.Class,其中包含仅指向jsni方法/字段的字段和方法访问器。:)