Skip to content

Instantly share code, notes, and snippets.

@dungdm93
Created September 1, 2015 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dungdm93/323b73803d96a0230554 to your computer and use it in GitHub Desktop.
Save dungdm93/323b73803d96a0230554 to your computer and use it in GitHub Desktop.
[Java 8] Constructor Reference example
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