전달 된 다항식에 의존하는 CRC 알고리즘과 "crc8"또는 "crc16"또는 "crc32"가 포함 된 s
문자열을 인스턴스화하는 코드가 있습니다.reflection + 생성자에 대한 도움말
클래스 CRC8
, CRC16
및 CRC32
모든 클래스 CRC
를 확장하고 인터페이스 HashAlgorithm
를 구현합니다. 각각은 생성자 CRCx(int polynomial)
을 가지고 있습니다.
Type mismatch:
cannot convert from Constructor<HashFactory.CRC16>
to Constructor<HashFactory.CRC>
하는 사람이 이유를 설명하고 나에게이 문제를 해결할 수 있도록 도와 줄 수 :
내 문제는 내가 getConstructor 메소드() 라인의 3에이 오류가있다?
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;
}
리플렉션을 사용하는 특별한 이유가 있습니까? –
음, 어, 나는 이유가 있었는데, 지금 생각할 수 없다. "kd304"는 좋은 지적입니다. –
팩토리 패턴을 사용하고 새로 초기화 된 HashAlgorithm을 반환하는 것은 어떻습니까? 그런 다음 컴파일 시간을 확인하고 약간 더 빠르게 실행해야합니다. –