dimanche 1 mars 2020

::/lambda alternative: get Method safely in java 1.7

The code is wanted to be compatible with most devices, so it is written in java 1.7.

similar interfaces are used in code for an event system as "listeners"

interface
Updatable
{
  void
  update();
}

Events are called → call all "listeners"

spot(Method, Object... event);

for Updatable for example spotting an update is simple in java 1.8

spot(Updatable::update);
//or
spot(s->System.out.print(s), "Easy. Now let's save our planet!");

Attempts. Because this option is unavailable, two options are to consider. Both are using reflection (unsafe) to find out the Method to call

//util methods
static public @Nullable Method
method(Class<?> of, String name, Class... args)
{
  try { return of.getDeclaredMethod(name, args); }
  catch(Exception e)
  {
    Log.v(of.getSimpleName(),
          "method "+ name + Arrays.toString(args)
          +" does not exist in "+ of.getName(), e);
    return null;
  }
}

static @NotNull Class<?>[]
classes(@NotNull Object[] of)
{
  Class<?>[] type=new Class[of.length];
  for(int i=0; i<type.length; ++i)
  {
    type[i]= of[i].getClass();
  }
  return type;
}

0] finding out the Method by name each time

void
spot(Class<?> spotted_class, String name,
     Object... event)
{
  spot(method(spatted_class, name, classes(signal)),
       signal);
}

//usage
spot(Updatable.class, "update");

1] creating a constant for every method

static final Method
UPDATE= method(Updatable.class, "update");

//usage
spot(UPDATE);

Questions. Is there a

  1. safer
  2. simpler

way to implement my goal?





Aucun commentaire:

Enregistrer un commentaire