I am working with Java Spring framework and JWT - Java Web Tokens. I have below class
import java.util.function.Function;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import app.com.javainuse.config.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class Test {
public static void main(String[] args) {
User u=new User("javainuse", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6",new ArrayList<>());
UserDetails ud=u;
JwtTokenUtil jwtTokenUtil=new JwtTokenUtil();
String token = jwtTokenUtil.generateToken(ud);
Test t=new Test();
System.out.println(t.getClaimFromToken(token, Claims::getSubject));
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
System.out.println(claims.toString());
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey("javainuse").parseClaimsJws(token).getBody();
}
}
I am not able to understand statement containing this Claims::getSubject in main method. It gets passed to a functional interface Named Function<Claims,T> claimresolver. How does a method reference getSubject without implementation able to return subject from claims object in getClaimFromToken method ? When we pass method reference to a Functional Interface we the method must have body wight ? but Claims is an interface and getSubject does not have a body then how does "claimsResolver.apply(claims);" is able to get subject value ?
You're right that the
Claims::getSubjectsyntax here is passing a method reference to theFunctioninterface, rather than implementing the full lambda expression.The key to how this works is that
Claimsis an interface that extends theClaimsinterface from theio.jsonwebtokenlibrary.That
io.jsonwebtoken.Claimsinterface defines various getter methods likegetSubject(),getIssuer()etc. without providing implementations.So when we call:
We are providing a reference to the
getSubject()method on theio.jsonwebtoken.Claimsinterface.Even though the interface doesn't provide an implementation, at runtime the
claimsobject will actually be an instance of some class that implements theio.jsonwebtoken.Claimsinterface and provides a concrete implementation ofgetSubject().When
claimsResolver.apply(claims)is called, it will invoke that underlyinggetSubject()method on theclaimsinstance, which returns the subject value.So in summary:
Claims::getSubjectprovides a reference to the interface methodclaimsobject provides an implementation of that interfaceclaimsResolver.apply(claims)is able to call the implementedgetSubject()method to return the value