简体   繁体   English

Java:在运行时和编译时向类添加字段吗?

[英]Java: Adding fields to class at runtime & compiletime?

Rewriting this for greater clarity. 重写此代码可以使其更加清晰。

R.java is a great resource in Android. R.java是Android中的重要资源。 It's basically cheating, by dynamically changing at compile time to provide access to all of your resources. 通过在编译时动态更改以提供对所有资源的访问,这基本上是作弊。

It would be awesome to have something like this available for applications running core Java. 对于运行核心Java的应用程序提供类似的功能真是太棒了。 However, I understand that R.java does some crazy hackery to make this work. 但是,我了解到R.java确实做了一些疯狂的黑客工作才能完成这项工作。

So, here are my goals. 所以,这是我的目标。 If anyone has any ideas to point me in the right direction, that would be great. 如果任何人有任何想法向我指出正确的方向,那将是很好的。

1) Public static fields that link to resources defined by the developer. 1)链接到开发人员定义的资源的公共静态字段。

2) The fields are created dynamically, ie they are not hard-coded into existence. 2)这些字段是动态创建的,即它们没有被硬编码为存在。

3) The dynamic creation occurs at compile time, so the following statement would be accepted by the compiler: MyRJava.resourceName. 3)动态创建在编译时发生,因此编译器将接受以下语句:MyRJava.resourceName。

Is this even remotely possible? 这甚至可以实现吗? Where would I start looking to see if it can be done? 我将在哪里开始寻找是否可以完成?

Java doesn't support this, but Groovy does . Java不支持此功能,但Groovy支持。 As a Java developer, you should have no problem picking up Groovy for something like this. 作为Java开发人员,选择Groovy来完成类似这样的工作应该没有问题。 One of the nice things about Groovy is that it coexists very well with Java code. Groovy的优点之一是它可以与Java代码很好地共存。 Where I work, we frequently go back and forth between the two languages. 在我工作的地方,我们经常在两种语言之间来回切换。

Remotely possible. 遥不可及。 We were successfully using APT and Maven to set up a compile time goal which generates additional Java classes. 我们已经成功地使用APT和Maven设置了生成其他Java类的编译时间目标。 This however not a real dynamic class generation, as we're doing everything in compile time. 但是,这不是真正的动态类生成,因为我们在编译时正在做所有事情。

The advantage is that after saving (and the code generator has run), you can use all the genarated fields normally (ie in autocomplete, and so on). 优点是保存后(并且代码生成器已运行),您可以正常使用所有生成的字段(即自动完成等)。

It is also possible to create something similar in runtime, ie you can create a class file, compile it, and then get access to its fields and methods via reflection. 也可以在运行时创建类似的东西,即,您可以创建一个类文件,对其进行编译,然后通过反射来访问其字段和方法。 In this case however accessing to the genrated fields are more problematic - and finally you'd better go with a simple Map to hold "resource ids" like R.java. 但是,在这种情况下,访问生成的字段会遇到更多问题-最后,您最好使用一个简单的Map来保存R.java之类的“资源ID”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM