EncodingErrorMsg { static @Nullable String msg(String chars, byte[] bytes, Charset charset) { int unrepresentable = chars.indexOf(UNREPRESENTABLE); if (unrepresentable == -1) { return null; } ByteBuffer byteBuf = ByteBuffer.wrap(bytes); CharBuffer charBuf = CharBuffer.allocate(chars.length()); CoderResult result = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(byteBuf, charBuf, true); if (!result.isError()) { return null; } else { return new EncodingErrorMsg(chars, byteBuf, charset, unrepresentable).message.toString(); } } private  EncodingErrorMsg(String chars, ByteBuffer byteBuf, Charset charset, int unrepresentable);   }
@Test public void canUseUnrepresentableOnPurpose() throws UnsupportedEncodingException { String pathologic = new String(new char[]{EncodingErrorMsg.UNREPRESENTABLE}); byte[] pathologicBytes = pathologic.getBytes(StandardCharsets.UTF_8); String pathologicMsg = EncodingErrorMsg.msg(pathologic, pathologicBytes, StandardCharsets.UTF_8); Assertions.assertThat(pathologicMsg).isNull(); }