/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; /** * The code sample illustrates changes in reflection API linked * default methods. Since Java SE 8, a new method is added into class * java.lang.reflect.Method, with which we could * reflectively determine if a method is a default method provided by an * interface or not (Method.isDefault()). */ public class Reflection { /** Base interface to illustrate new reflection API. * * @see Dog */ public interface Animal { default void eat() { System.out.println(this.getClass().getSimpleName() + " eats like an ordinary animal"); } default void sleep() { System.out.println(this.getClass().getSimpleName() + " sleeps like an ordinary animal"); } void go(); } /** * Dog class to illustrate new reflection API. We can see that: * */ public static class Dog implements Animal { @Override public void go() { System.out.println("Dog walks on four legs"); } @Override public void sleep() { System.out.println("Dog sleeps"); } } public static void main(String[] args) throws NoSuchMethodException { Method[] methods = {Dog.class.getMethod("eat"), Dog.class.getMethod("go"), Dog.class.getMethod("sleep")}; final Dog dog = new Dog(); Arrays.asList(methods).stream().forEach((m) -> { System.out.println("Method name: " + m.getName()); System.out.println(" isDefault: " + m.isDefault()); System.out.print(" invoke: "); try { m.invoke(dog); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { } System.out.println(); }); } }