An Interface equivalent for reflection
Remi Forax
forax at univ-mlv.fr
Tue May 7 17:58:44 UTC 2019
This is the wrong list, this list is about about the implementation of the core Java libraries, you are looking for the santa mailing list.
Anyway, in your case, Java has already the notion of functional interface, an interface with one abstract method that can be used to store a reference to a method.
@FunctionalInterface
interface Transform {
String apply(String s);
}
class Main {
private static String highlight(String s) {
return "*" + s + "*";
}
public static void algorithm(Transform transform) {
...
}
public static void main(String s) {
Transform transform = Main::highlight;
// or
algorithm(Main::highlight);
}
}
[if you have more questions, i will be happy to answer on my direct email address]
regards,
Rémi
----- Mail original -----
> De: "Timothy Schommer" <timothy2 at iastate.edu>
> À: "core-libs-dev" <core-libs-dev at openjdk.java.net>
> Envoyé: Mardi 7 Mai 2019 14:58:05
> Objet: An Interface equivalent for reflection
> I would like to request the addition of an Interface equivalent usable for
> reflection. Sometimes when writing a program it is desirable to have the
> client program specify how your program should behave in a specific
> scenario. Java's reflection can be used to obtain this method, but only if
> the client implements it. In this case, a structure for guaranteeing that
> the client implements the method is desirable. Interfaces come to mind for
> this usage, as the program can type-check the client to ensure that they
> implement it. However, what is not always so desirable about using an
> Interface for this is the fact that all Interface methods must be public.
> You may want to guarantee that the client has access to a method, but you
> might not necessarily want every class that uses the client to have access
> to the method. Having the client use reflection to pass the method in,
> while providing a default implementation yourself is another possibility,
> but it is impossible to completely type-check the method passed in until
> you try to run it and throw an exception if it doesn't match. For
> this reason I would like to request an Interface equivalent designed for
> use with Java's reflection.
>
> I understand that, in general, reflection is intended as a bit of a
> last-ditch back door access, and that you may not wish to encourage more
> general usage of reflection, but I feel that implementing this will make it
> so that if people do choose to use reflection for something along the lines
> of what I described above, then they can do so while minimizing the
> likelihood of of throwing an exception due to an improper of non-existent
> method.
>
> Thank you for your time,
> Timothy Schommer
More information about the core-libs-dev
mailing list