帮助反射+构造函数

Jas*_*n S 1 java reflection constructor

我有代码我正在努力实例化依赖于传入的多项式的CRC算法,以及s包含"crc8"或"crc16"或"crc32" 的字符串.

该班CRC8,CRC16CRC32所有的扩展类CRC和实现接口HashAlgorithm.他们每个人都有一个构造函数CRCx(int polynomial).

我的问题是,我在所有3个getConstructor()行上都出现了这个错误:

Type mismatch: 
  cannot convert from Constructor<HashFactory.CRC16> 
  to Constructor<HashFactory.CRC>
Run Code Online (Sandbox Code Playgroud)

谁能帮助解释原因并帮助我解决这个问题?

    int polynomial; // assign from somewhere
    Constructor<CRC> crc = null;
    if ("crc8".equals(s))
    {
        crc = CRC8.class.getConstructor(Integer.TYPE);
    }
    if ("crc16".equals(s))
    {
        crc = CRC16.class.getConstructor(Integer.TYPE);
    }
    if ("crc32".equals(s))
    {
        crc = CRC32.class.getConstructor(Integer.TYPE);
    }
    if (crc != null)
    {
        CRC crcInstance = crc.newInstance(polynomial);
        return (HashAlgorithm) crcInstance;
    }
Run Code Online (Sandbox Code Playgroud)

aka*_*okd 5

尝试

    int polynomial; // assign from somewhere
    if ("crc8".equals(s)) {
            return new CRC8(polynomial);
    } else
    if ("crc16".equals(s)) {
            return new CRC16(polynomial);
    } else
    if ("crc32".equals(s)) {
            return new CRC32(polynomial);
    }
Run Code Online (Sandbox Code Playgroud)

要么

package tests;
import java.lang.reflect.Constructor;
public class Construct {
    static interface CRC { }
    static class CRC8 implements CRC {
        public CRC8(int p) { }
    }
    static class CRC16 implements CRC {
        public CRC16(int p) { }
    }
    static class CRC32 implements CRC {
        public CRC32(int p) { }
    }
    public static CRC getAlg(String s, int polynomial) {
        try {
            Class<?> clazz = Class.forName("tests.Construct$" + s.toUpperCase());
            Constructor<?> c = clazz.getConstructor(Integer.TYPE);
            return CRC.class.cast(c.newInstance(polynomial));
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new AssertionError("Unknown algorithm: " +s);
    }
    public static void main(String[] args) throws Exception {
        System.out.println(getAlg("crc8", 0));
        System.out.println(getAlg("crc16", 0));
        System.out.println(getAlg("crc32", 0));
        System.out.println(getAlg("crc48", 0));
    }
}
Run Code Online (Sandbox Code Playgroud)

"工厂"模式:

    public static HashAlgorithm getHashAlgorithm(String s, int polynomial) {
        if ("crc8".equals(s)) {
            return new CRC8(polynomial);
        } else
        if ("crc16".equals(s)) {
            return new CRC16(polynomial);
        } else
        if ("crc32".equals(s)) {
            return new CRC32(polynomial);
        }
        throw new AssertionError("Unknown algorithm: " +s);
    }
Run Code Online (Sandbox Code Playgroud)

它可以通过其他几种方式完成(例如,算法的HashMap到可复制的CRC类等)