String.valueOf() vs. Object.toString()

后端 未结 10 782
挽巷
挽巷 2020-12-12 10:21

In Java, is there any difference between String.valueOf(Object) and Object.toString()? Is there a specific code convention for these?

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 10:54

    I can't say exactly what the difference is but there appears to be a difference when operating at the byte level. In the following encryption scenario Object.toString() produced a value that couldn't be decrypted whereas String.valueOf() worked as intended ...

    private static char[] base64Encode(byte[] bytes) 
    {   
        return Base64.encode(bytes);
    }
    
    private static String encrypt(String encrypt_this) throws GeneralSecurityException, UnsupportedEncodingException 
    {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    
         //THIS FAILED when attempting to decrypt the password
        //return base64Encode(pbeCipher.doFinal(encrypt_this.getBytes("UTF-8"))).toString(); 
    
        //THIS WORKED
        return String.valueOf(base64Encode(pbeCipher.doFinal(encrypt_this.getBytes("UTF-8"))));
    }//end of encrypt()
    

提交回复
热议问题