如何指定应在Java中应用Annotation的字段类型?

时间:2015-06-14 04:09:55

标签: java android reflection annotations

我正在创建一个简单的注释,以帮助我扩展Android应用程序中的设置。注释是这样的:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CoreSettings {
    String name() default "";
}

我想确保它只会在类型扩展名为 BaseSettings 的自定义类的字段中使用。在下面的示例中,MainSettings扩展了抽象类BaseSettings。

public class MainActivity extends BaseActivity {

    @CoreSettings("prefs")
    MainSettings settings;


    (...)

}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

是的,如果您在错误类型的字段上编写注释,则可能导致编译器发出错误消息。

您不能仅使用@Target元注释来执行此操作。此外,您需要编写注释处理器。注释处理器将检查源代码中注释@CoreSettings的每次出现,如果将@CoreSettings应用于未扩展的类型BaseSettings,它将发出错误(就像任何其他编译器错误一样)-processor ... 1}}。这是一个简短的,简单的注释处理器。

运行注释处理器时只会收到编译时警告,但是可以在项目的构建文件中将def DecodedWebsockRecieve(stringStreamIn): byteArray = stringStreamIn datalength = byteArray[1] & 127 indexFirstMask = 2 if datalength == 126: indexFirstMask = 4 elif datalength == 127: indexFirstMask = 10 masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]] indexFirstDataByte = indexFirstMask + 4 decodedChars = [] i = indexFirstDataByte j = 0 while i < len(byteArray): decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) ) i += 1 j += 1 return ''.join(decodedChars) def EncodeWebSockSend(socket,data): bytesFormatted = [] bytesFormatted.append(129) bytesRaw = data.encode() bytesLength = len(bytesRaw) if bytesLength <= 125 : bytesFormatted.append(bytesLength) elif bytesLength >= 126 and bytesLength <= 65535 : bytesFormatted.append(126) bytesFormatted.append( ( bytesLength >> 8 ) & 255 ) bytesFormatted.append( bytesLength & 255 ) else : bytesFormatted.append( 127 ) bytesFormatted.append( ( bytesLength >> 56 ) & 255 ) bytesFormatted.append( ( bytesLength >> 48 ) & 255 ) bytesFormatted.append( ( bytesLength >> 40 ) & 255 ) bytesFormatted.append( ( bytesLength >> 32 ) & 255 ) bytesFormatted.append( ( bytesLength >> 24 ) & 255 ) bytesFormatted.append( ( bytesLength >> 16 ) & 255 ) bytesFormatted.append( ( bytesLength >> 8 ) & 255 ) bytesFormatted.append( bytesLength & 255 ) bytesFormatted = bytes(bytesFormatted) bytesFormatted = bytesFormatted + bytesRaw socket.send(bytesFormatted) 命令行参数添加到javac。