java动态属性,Java:动态属性

Ladies & Gentlemen,

I´m new to Java, forgive me if it´s obvious, but I haven´t found much about it.

I´d like to create dynamic properties (variables) for a class at runtime (define an object that can be altered at runtime by adding or changing properties and methods).

Reason: I want to store a data model in GAE that can be extended dynamically after compilation of the app (yes, the DataStore allows that). What properties should be added are stored in the DataStore as well (It´s like using Robots to built Robots...funny).

Python allows me to add properties at Runtime. Groovy seems to allow that, too. The only thing in the "pure" Java world indicating in that direction seems to be "Dynamic Proxies".

But I couldn´t figure out yet if they do the trick.

解决方案

Java doesn't have the capability to dynamically add properties. Nor does it have the ability to dynamically create classes at runtime or change them at runtime. Java is strongly and statically typed. The best you can do is put such properties into a Map or similar.

Edit: Ok, apparently some clarifications are in order. The OP specifically mentioned GAE, which none of these methods will work on but I'll mention them since some seem to take exception to their absence.

The Java Compiler API (Java 6+) allows you to compile Java classes at runtime. Technically you could write out a Java source file to look exactly how you want, compile it and load it.

Java bytecode libraries can rewrite classes at runtime. This is used by such libraries as JPA (and others). You could modify classes this way.

What the OP is referring to however is a) in reference to working on GAE and b) more in the order of how Javascript allows you to modify classes or particular instances at runtime by dynamically adding, removing or change properties. Java certainly doesn't do this and specifically doesn't on the GAE.

The above is not an exception to this just like casting a class to char * in C++ so you can read private members doesn't mean C++ doesn't have private members. You're essentially bypassing the Java runtime with both of these methods even though they're part of Java.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值