[英]Is PublicKey and PrivateKey in java a Class or an Interface
正如我通過https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/PublicKey.ZFC35FDC70D5FC69D252EZ83A8 了解的那樣,它不能是接口。創建一個 object 但使用代碼
public static void main(String[] args) throws Exception {
try
{
KeyPairGenerator kpr=KeyPairGenerator.getInstance("EC");
SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
ECGenParameterSpec ecgps=new ECGenParameterSpec("secp256r1");
kpr.initialize(ecgps,sr);
KeyPair kp=kpr.generateKeyPair();
PublicKey p=kp.getPublic();
System.out.println(p);
}
catch(Exception e)
{
throw new RuntimeException(e);
}
它仍在工作。誰能解釋一下這個如何??我正在使用 Eclipse IDE(openjdk12)。
該實現有一些實現PublicKey
接口的 class。 在調用generateKeyPair
期間,實現 class 被創建,並在返回給您之前轉換為PublicKey
。 這是一個基本的“工廠設計模板”。
例子:
// you see this
interface Foo
{
void bar();
}
// we hide this somewhere and do not provide the code
class FooImpl
{
void bar() { ... }
}
// This is the factory that you'll be using
// it will provide you with an instance that implements Foo
class FooGenerator
{
Foo generate() { return new FooImpl(); }
}
嘗試調用p.getClass().getName()
並親自查看!
PublicKey
和PrivateKey
是接口,您可以從鏈接文檔中看到。
但是一個接口不能創建一個 object...
這實際上不是真的(默認方法可以創建對象),但這不是正在發生的事情。 object 由KeyPairGenerator
創建。 密鑰對中的對象將是實現PublicKey
和PrivateKey
接口的類的實例。
就像:
Map<String> map = new HashMap<>();
Map
是一個接口,但是HashMap
是一個class; 分配給變量的 map 是HashMap
的一個實例。 正在使用的KeyPairGenerator
實現中的代碼將以類似的方式創建對象,這些對象是實現PublicKey
和PrivateKey
的類的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.