Simple puzzle NPE (String)

We had training related to java, and was short example of code, like that :

void todoSomethig(Agent agent){
  if(agent!=null && agent.getName().length() > 0){
    System.out.println(agent.getFullName())   
 }
}

and all developers tried to find places where NPE can be thrown. Yes, we found that name can be null

 agent.getName()

also that agent.getFullName() can throw NPE. But I asked, next question :

Can  method length()  throw NPE ???

So, here is short description how that can be implemented 🙂

OK, we should know where method length() is declared, short investigation can show us that method length() is from interface CharSequence.

OK, good, BUT how can we overwrite this method in final class String ???

The answer we cannot! (Reflection we cannot use for that task)

OK, So, we have full information and can start develop our puzzle with throwing NPE in length() method.

First step is develop String and StringUtils.

public class String implements CharSequence {
    final Integer length = null;
    @Override
    public CharSequence subSequence(int start, int end) {
        return null;
    }
 
    @Override
    public int length() {
        return length;
    }
 
    @Override
    public char charAt(int index) {
        return 0;
    }
}
public class StringUtils {
 
    @SuppressWarnings("unchecked")
    public static <C extends CharSequence> C getString(java.lang.String string) {
        if (!"".equals(string)) {
            return (C) "";
       }
        return (C) new String();
    }
}

and  Second is just a main method with calling util class.

/**
 * @author 
 */
public class Main {

 public static void main(String[] args) {
   String test = StringUtils.getString("test");
   System.out.println(test.length()); <-- All is good
   System.out.println(StringUtils.getString(test).length()); <--NPE
 }
}

SO, this is simple trick 🙂 to get NPE in length() method 🙂

What is the advice, try to think out of the scope 🙂

Thanks!