开发者

In Java: How to access static property of dynamically referenced class?

In Java: How to access static property of dynamically referenced class? I'm giving a short example:

AppleTree.areTheyAllGrown=true;

I simply want to dynamically reference the class of the static property 'areTheyAllGrown' This static property can be member of AppleTree or may be member of some other class, which of cource will also have the same named static property: 'areTheyAllGrown'.

As long as my application logic requires me to have many other tree types like CherryTree, ApricotTree and etc., it means that interface TreeBehaviour would not be sufficient solution, because by setting 'areTheyAllGrown' specifically 开发者_JAVA百科of AppleTree, I want to mark let's say: only my AppleTree instances for that, not all Tree instances. See?

You would say: make an AppleTreeImpl interface and put the property in there... well.. that would force hell of an interfaces, to create only for one property...Impl Interface for all my different tree types? Isn't there a more short solution?

Ofcourse I see many other ways to implement the whole stuff, and to work around the need of dynamic referencing to a class, however, I am interested If I can do it particulary by this method. Also without excess use of interfaces or additional helper classes, nor public properties outside the Tree classes.


I'd suggest putting this outside the classes. In another class GrowingRegistry, where you can have a map - Map<Class, Boolean>. And so you can do:

GrowingRegistry.setAllGrown(AppleTree.class, true);

Even better, you can implement an interface Tree that defines getTreeType() for example, and have the map Map<TreeType, Boolean>, where TreeType is an enum. So:

GrowingRegistry.setAllGrown(TreeType.APPLE, true);

To extend further, you can have GardenProperties object which holds all properties for the "garden".

And as I mentioned garden - the whole problems comes from the fact that you want to track all instantiated objects. And it is you who instantiates them, isn't it? So you can put all instances in your collections. For example:

Garden garden = new Garden();
garden.add(new AppleTreeImpl());
garden.add(new CherryTreeImpl());

There you can store the instances in a List or Map, and also use the garden for holder of all properties.


If you have an object, you could just do what you were proposing on the object directly.

If you have a class you could use reflection:

try {
    treeClass.getField("areTheyAllGrown").set(treeClass, true);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
    // Do whatever you want with the error
    // e.g.: e.printStackTrace();
    // Or you could add a throws declaration
};


Well, reflection is the only way to do what he described. Doing something else is surely a better idea. I'd suggest a Map, Boolean> (which in fact is a Set).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜