commons-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Joerg Schaible (JIRA)" <>
Subject [jira] [Commented] (CRYPTO-74) Full class names make code more difficult to update
Date Thu, 23 Jun 2016 07:59:16 GMT


Joerg Schaible commented on CRYPTO-74:

SPI is a very old Java concept, it was part of the spec since 1.2 (IIRC), but there was no
official API. This changed with Java 7 (java.util.ServiceLoader - although Image IO of Java
6 does also contain an implementation that can be used independently). However, I am not aware
that we use the mechanism yet anywhere in Commons.

A very simple implementation to get a map of all available implementations boils down to

ServiceLoader<CryptoRandom> serviceLoader = ServiceLoader.load(CryptoRandom.class);
Map<String, CryptoRandom> map = new HashMap<>();
for(CryptoRandom cr : serviceLoader) {
    String name = cr.getClass().getAnnotation(CryptoName.class).getValue(); // NPE for missing
annotation ...
    map.put(name, cr);

All that is required is a file named META-INF/services/org.apache.commons.crypto.random.CryptoRandom
containing the implementation names on separate lines:


That's it.

> Full class names make code more difficult to update
> ---------------------------------------------------
>                 Key: CRYPTO-74
>                 URL:
>             Project: Commons Crypto
>          Issue Type: Improvement
>            Reporter: Sebb
> The method CryptoRandomFactory.getCryptoRandom uses the value of a property as the full
name of the CryptoRandom class to be instantiated.
> This is inherently non-portable if the code package names should ever be changed in future.
> One way round this is to add a constant alias for the embedded implementations.
> For example:
> public static final String OPENSSL_RANDOM = "OpensslCryptoRandom";
> public static final String JAVA_RANDOM = "JavaCryptoRandom";
> ...
> If the COMMONS_CRYPTO_SECURE_RANDOM_CLASSES_KEY string does not contain a full class
name, then the code would preprend the appropriate package name (or there could be a lookup
> This would also work for the case where the class is provided as a system property value.
> Another advantage of this method is that it simplifies the user code.
> Similar considerations apply to all other factories which use class name strings.
> [Note: the constants must not contain the full package names as that would result in
a binary incompatibility if the names changed.]

This message was sent by Atlassian JIRA

View raw message