Java Pass Method as Parameter

后端 未结 16 996
滥情空心
滥情空心 2020-11-22 02:17

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I\'ve

16条回答
  •  盖世英雄少女心
    2020-11-22 02:56

    Example of solution with reflection, passed method must be public

    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationTargetException;
    
    public class Program {
        int i;
    
        public static void main(String[] args) {
            Program   obj = new Program();    //some object
    
            try {
                Method method = obj.getClass().getMethod("target");
                repeatMethod( 5, obj, method );
            } 
            catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                System.out.println( e ); 
            }
        }
    
        static void repeatMethod (int times, Object object, Method method)
            throws IllegalAccessException, InvocationTargetException {
    
            for (int i=0; i

提交回复
热议问题