与构造函数链接混淆

时间:2014-11-20 23:20:55

标签: java constructor

我试图理解几个构造函数链接,我知道从同一个类的另一个构造函数调用构造函数称为构造函数链接,

当我们在构造函数中使用它时,我们实际上正在调用我们已经定义的另一个构造函数,但是我想要理解的程序很奇怪,

public AESCipher(Key key) {
        this(key.getEncoded());
    }

    /**
     * Create AESCipher based on existing {@link Key} and Initial Vector (iv) in bytes
     *
     * @param key Key
     */
    public AESCipher(Key key, byte[] iv) {
        this(key.getEncoded(), iv);
    }

    /**
     * <p>Create AESCipher using a byte[] array as a key</p>
     * <p/>
     * <p><strong>NOTE:</strong> Uses an Initial Vector of 16 0x0 bytes. This should not be used to create strong security.</p>
     *
     * @param key Key
     */
    public AESCipher(byte[] key) {
        this(key, INITIAL_IV);
    }

    private AESCipher(byte[] key, byte[] iv) {
        try {
            this.secretKeySpec = new SecretKeySpec(key, "AES");
            this.iv = new IvParameterSpec(iv);
            this.cipher = Cipher.getInstance(ALGORITHM_AES256);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw Throwables.propagate(e);
        }
    }

在第一个构造函数中,这一行使用this(key.getEncoded()),这个构造函数是这行调用的吗?之前没有构造函数,实际上没有带有一个参数的构造函数。

并且在第3个构造函数中,只有一个byte[]类型的参数,这就是里面发生的事情,

this(key, INITIAL_IV);

它链接了一个带有两个参数的构造函数,一个类型为key,类型为byte[],所以它链接了这个构造函数AESCipher(Key key, byte[] iv),这很好,但仍然......在第一个构造函数中发生了什么,以及为什么首先需要4个构造函数。

P.S:我刚才没有发布这个问题,我花了4小时的时间试图了解发生了什么,但它太混乱了。

这是完整的代码,

https://github.com/mike-ensor/aes-256-encryption-utility/blob/master/src/main/java/com/acquitygroup/encryption/AESCipher.java

1 个答案:

答案 0 :(得分:5)

第一个构造函数调用第三个构造函数:public AESCipher(byte[] key)

至于为什么首先有4个构造函数,它的目的是封装处理将Key转换为byte[]的逻辑,并允许用户使用不同的初始向量,如果他们这样选择。

相关问题