Created
September 1, 2015 08:22
-
-
Save dungdm93/323b73803d96a0230554 to your computer and use it in GitHub Desktop.
[Java 8] Constructor Reference example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface NoArgConstructor<T> { | |
T foo(); | |
} | |
interface ArgConstructor<T, U> { | |
T bar(U arg); | |
} | |
interface MultiArgsConstructor<T, U> { | |
T magic(U... arg); | |
} | |
public class ConstructorReferenceDemo { | |
private String content; | |
private String[] contents; | |
public ConstructorReferenceDemo() { | |
this.content = "created by constructor reference"; | |
} | |
public ConstructorReferenceDemo(String content) { | |
this.content = content; | |
} | |
public ConstructorReferenceDemo(String... contents) { | |
this.contents = contents; | |
} | |
public static void main(String... args) { | |
NoArgConstructor<ConstructorReferenceDemo> noArgConstructor = ConstructorReferenceDemo::new; | |
System.out.printf("No arg constructor : %s%n%n", noArgConstructor.foo().getContent()); | |
ArgConstructor<ConstructorReferenceDemo, String> argConstructor = ConstructorReferenceDemo::new; | |
System.out.printf("Arg constructor : %s%n%n", argConstructor.bar("This is an argument").getContent()); | |
MultiArgsConstructor<ConstructorReferenceDemo, String> multiArgsConstructor = ConstructorReferenceDemo::<String>new; | |
System.out.printf("Multi args constructor : %s%n", multiArgsConstructor.magic("One", "Two", "Three").getContents().length); | |
} | |
public String getContent() { | |
return content; | |
} | |
public String[] getContents() { | |
return contents; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment