Use reflection to repeat classes

I have a class with numerous parameters of different types. I want to iterate over all elements of type A and run certain functions (A.doSomething ())

It doesn't even compile: conversion from field to XPathDataElement is illegal

Field[] fields = this.getClass().getDeclaredFields();
  for (Field field : fields) {
     if (field. getType().getName().equals(XPathDataElement.class.getName()))
        {               
                tmp = (XPathDataElement)field; // Doesn't compile
                sb.append(field.getName() + ":"); 
                tmp.update();
        }
    }

Thanks!

+3
source share
4 answers

It's hard to debug your code unless you say what is wrong with it.

Two things that I see:

  • There is no need to compare strings to determine if the field type is the correct class.

    if (field.getType().equals(XPathDataElement.class))
    

    must work.

    : , XPathDataElement; . , XPathDataElement, Class.isAssignableFrom(Class).

    if (XPathDataElement.class.isAssignableFrom(field.getType()))
    

    .

  • , - ? , Field.get(Object) - , . , get(), , ; this ( ),

    XPathDataElement tmp = (XPathDataElement) field.get(this);
    
+10

, .

:

this.x.doSomething();
this.y.doSomething();
this.z.doSomething();

, :

for (A a : new A[] {
    this.x, this.y, this.z
}) {
    a.doSomething();
}
+2

:

  • , .

    field.getType(). (XPathDataElement.class)

  • , isAssignableFrom(java.lang.Class) , ,

    XPathDataElement.class.isAssignableFrom(field.getType())

  • You repeat the fields , not the method . Your question makes me suggest that you want the latter, and if so, use:

    this.getClass (). GetDeclaredMethods ()

+1
source

It seems you are not assigning anything objyou passed in XPathDataElementin the loop.

You probably want to do something like this:

tmp = (XPathDataElement)field.get(this);
0
source

Source: https://habr.com/ru/post/1705969/


All Articles