[java] Adding fields at runtime using reflection

Started by
7 comments, last by OrangyTang 15 years, 5 months ago
Let's say I have this empty class:

public class Being {
}

Is it possible to add fields to objects of this class at run-time? I've been searching the reflection API, but it seems all I can do with that is getting information about fields, not adding. What I'm trying to achive:

Class cls = Class.forName("Being");

/* Adds a public integer field named "num" */
cls.setField(new Field("num", Integer.TYPE));

/* ...or something like that, maybe even: */
Field num = cls.addField();
num.setInt(22);

Advertisement
consider using a map?
Quote:Original post by AAA
consider using a map?


Yes, that's my plan B, I just wanted to know if the above was possible.
To the best of my knowledge you can't do that and it wouldn't make much sense to be able to do it. Reflection does exactly what the name suggests, reflect.

Can you imagine instantiating a class object, then adding fields to its class? What would that even mean?
Quote:Original post by AAA
To the best of my knowledge you can't do that and it wouldn't make much sense to be able to do it. Reflection does exactly what the name suggests, reflect.

Can you imagine instantiating a class object, then adding fields to its class? What would that even mean?


Perhaps the word I was looking for was "compiling" instead of "reflection". I've done projects in C# where I was able to emit methods and fields at run-time (using ICodeCompiler), but I couldn't find the same functionality in Java.

Anyway, I going for the map-approach now.
BCEL. The other way is to invoke javac itself.

Although this type of code generation has yet to convince me of its benefits from application design perspective.
Quote:Original post by Antheus
BCEL. The other way is to invoke javac itself.

Although this type of code generation has yet to convince me of its benefits from application design perspective.


Cool, thanks for the link.
I'm currently doing something like this in one of my apps:

class DynaFieldBean {  Map<String, Field> fields = new HasMap<String, Field>();  public Field createFieldWithName(String fieldName) {    Field f = new Field();    fields.put(fieldName, f);    return f;  }  public Field getField(String fieldName) {    Field f = fields.get(fieldName);    if (f == null) {      f = createFieldWithName(fieldName);    }    return f;  }}


This should do what you want, with minimal overhead. Only thing not taken into account here is the various types of field you would be able to create. For this, you would have to add some extra functionality.
Quote:Original post by Antheus
BCEL. The other way is to invoke javac itself.

Although this type of code generation has yet to convince me of its benefits from application design perspective.

Alternativly if you're using Java 1.6 or later you can use the newly added Java Compiler API.

This topic is closed to new replies.

Advertisement