4

Sometimes I need to test which class has declared some variable(s), is there another way how to test that, if concrete class contains variable with some name

try {
   testLocalVariable = (String) (this.getClass().getDeclaredField("testVariable").get(this));
} catch (NoSuchFieldException ex) {
} catch (SecurityException ex) {
} catch (IllegalArgumentException ex) {
} catch (IllegalAccessException ex) {
}
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 3
    Can you give a little more background/context about the underlying problem you're trying to solve, as opposed to how you're trying to solve it? Also, are you looking for whether there's a member field with some name and type, or do you want to check equality of some instance as well? – jtoberon Jul 08 '11 at 20:21
  • What you described is pretty much the way to do it. However the scenario sounds a bit fishy. You can have legitimate reasons for doing what you're doing but 9 times out of 10 this pattern is the result of poor OO design. – biziclop Jul 08 '11 at 20:31
  • you could to it this way. dont forget to check super classes using getField() or recursion. – Ant Kutschera Jul 08 '11 at 21:06

2 Answers2

2

Classes have fields, not local variables.

You can use getDeclaredField() however this will not find fields declared by super classes.

You don't need lookup the fields value, if you don't get an exception the field is there.

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • thanks for Field..., there isn't problem set/get/check if exist, my question is if there isn't (in Java) another way, but I have for testing only value in String :-) – mKorbel Jul 08 '11 at 20:27
2

If I understand correctly, you use this code in a superclass to test if a subclass has a testVariable field.

Why don't you simply add a method like this?

 /**
  * Returns true if the object declares a testVariable field, false otherwise. Subclasses should
  * override this method
  */
protected boolean hasTestVariableField() {
    return false;
}

Seems much more OO to me, doesn't break encapsulation.

That said, I've not really understood why you needed this in the first place.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • data are stored (last knows and consist...) in Database, and for debuging I really don't want to jumping between classes (voids ... whatever..) then I wrote a few shortcuts – mKorbel Jul 08 '11 at 20:36
  • I forgot answer to "Why don't you simply add a method like this?" because there I needed set/get value :-) – mKorbel Jul 08 '11 at 20:42