Loading content...
Loading content...
Method reference ka matlab hai lambda expression ki jagah direct kisi method ka reference dena.
Syntax:
java
ClassName::methodName
objectReference::methodName
ClassName::newMethod reference teen type ke hote hain:
Static method reference
Instance method reference
Constructor reference
java
@FunctionalInterface
interface MyInterface {
public void m1();
}
public class MethodRef {
public static void m2() {
System.out.println("This is m2() method");
}
public static void main(String[] args) {
MyInterface mi = MethodRef::m2;
mi.m1();
}
}Yaha MethodRef::m2 directly m1() ke through call ho raha hai.
Lambda version hota:
java
MyInterface mi = () -> MethodRef.m2();Method reference short version hai.
plaintextCopy
public class InstanceMethodRef {
public void m1() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
InstanceMethodRef im = new InstanceMethodRef();
Runnable r = im::m1;
Thread t = new Thread(r);
t.start();
}
}Yaha object ka method reference diya gaya hai.
plaintext
class Doctor {
public Doctor() {
System.out.println("Doctor constructor....");
}
}
public class Test {
public static void main(String[] args) {
Supplier<Doctor> s = Doctor::new;
Doctor doctor = s.get();
System.out.println(doctor.hashCode());
}
}Doctor::new constructor ko reference karta hai.