samedi 8 août 2015

Is there any way to cast from Field to an Object? [duplicate]

This question already has an answer here:

So I need a way to check for the existence of an annotation on a field and if the annotation does exist, to cast that field to its actual type so I can access its methods. That might not make much sense so in code this is roughly what I'd like to be able to do.

There's a class that looks something like this:

class A 
{
  @CustomAnnotation
  public ServerA server = new ServerA();

  ...
}

And in another class I want to run through Class's A fields and check for the existence of the annotation and then perform some actions if it does

class Z 
{
  public void deleteFilesIfAnnotationExists()
  {
    Field[] fields = class.forName(A.class);
    for(Field field : fields)
    {
      if((field.getAnnotation(CustomAnnotation.class))!=null)
      {

        //the following code is wishful thinking
        if(field instanceof ServerA)
        {
          ServerA server = (ServerA) field; //what i really need to be able to do
          server.deleteFilesFromServerRootDir();
        }
      }
    }
  }
}

Is there anyway to do something similar to this or is it just wishful thinking? From the javadoc for Field it didn't seem obvious if it was.





Aucun commentaire:

Enregistrer un commentaire