1 /* 2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 */ 5 6 7 import java.lang.reflect.InvocationTargetException; 8 import java.lang.reflect.Method; 9 import java.util.Arrays; 10 11 /** 12 * The code sample illustrates changes in reflection API linked 13 * <b>default methods</b>. Since Java SE 8, a new method is added into class 14 * <b><code>java.lang.reflect.Method</code></b>, with which we could 15 * reflectively determine if a method is a default method provided by an 16 * interface or not (<b><code>Method.isDefault()</code></b>). 17 */ 18 public class Reflection { 19 20 /** Base interface to illustrate new reflection API. 21 * 22 * @see Dog 23 */ 24 public interface Animal { 25 26 default void eat() { 27 System.out.println(this.getClass().getSimpleName() + " eats like an ordinary animal"); 28 } 29 30 default void sleep() { 31 System.out.println(this.getClass().getSimpleName() + " sleeps like an ordinary animal"); 32 } 33 34 void go(); 35 } 36 37 /** 38 * Dog class to illustrate new reflection API. We can see that: 39 * <ul> 40 * <li> the {@link #go} and {@link #sleep} methods are not default. 41 * {@link #go} has not default implementation and {@link #sleep} method 42 * implementation wins as subtype (according with {@link Inheritance} rule 43 * 2) </li> 44 * <li> the {@link #eat} is a simple default method that not overridden 45 * in this class. 46 * </li> 47 * </ul> 48 */ 49 public static class Dog implements Animal { 50 51 @Override 52 public void go() { 53 System.out.println("Dog walks on four legs"); 54 } 55 56 @Override 57 public void sleep() { 58 System.out.println("Dog sleeps"); 59 } 60 } 61 62 public static void main(String[] args) throws NoSuchMethodException { 63 Method[] methods = {Dog.class.getMethod("eat"), Dog.class.getMethod("go"), Dog.class.getMethod("sleep")}; 64 final Dog dog = new Dog(); 65 66 Arrays.asList(methods).stream().forEach((m) -> { 67 System.out.println("Method name: " + m.getName()); 68 System.out.println(" isDefault: " + m.isDefault()); 69 System.out.print(" invoke: "); 70 try { 71 m.invoke(dog); 72 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { 73 } 74 System.out.println(); 75 }); 76 } 77 }