Test if a class contains an instance variable based on its name

Sometimes I need to check which class declared a variable (s), is there another way how to check this if a particular class contains a 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) { } 
+4
java class
Jul 08 '11 at 20:15
source share
2 answers

If I understand correctly, you are using this code in a superclass to check if the subclass has a testVariable class.

Why don't you just add such a method?

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

It seems to me a lot more OO, does not break encapsulation.

However, I really did not understand why you need this in the first place.

+2
Jul 08 '11 at 20:26
source share

Classes have fields, not local variables.

You can use getDeclaredField() , however this will not define fields declared by superclasses.

You do not need to look for the value of the fields, unless you get an exception, this is a field.

+2
Jul 08 '11 at 20:19
source share



All Articles