类型注解

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,//类型注解

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE//类型注解
}

类型注解: JDK1.8之后,关于元注解@Target的参数类型ElementType枚举值多了两个: TYPE_PARAMETER和TYPE_USE。

  • 在Java8之前,注解只能是在声明的地方所使用,Java8开始,注解可以应用在任何地方。
  • ElementType.TYPE_PARAMETER 表示该注解能写在类型变量的声明语句中(如:泛型声明)。
  • ElementType.TYPE_USE 表示该注解能写在使用类型的任何语句中。
class Generic<@MyAnnotation T>{//注解修饰的结构中没有提到T,其实也是可以通过反射来获取关于T的注解的
    //<@MyAnnotation T>这么做之后报错,因为也没有说@MyAnnotation可以修饰T这个结构


}

此时的@MyAnnotation为

@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotation {

    String value() default "hello";
}

进行修改;

@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER})
public @interface MyAnnotation {

    String value() default "hello";
}

这样就可以了
注意;

class Generic<@MyAnnotation T> {


    public void show() throws @MyAnnotation RuntimeException{


        ArrayList<@MyAnnotation String> list = new ArrayList<>();

        int num = (@MyAnnotation int) 10L;

    }
}

上面的程序中只有<@MyAnnotation T>不报错,其余用注解的地方都报错
解决方法,在MyAnnotation中加TYPE_USE,只要是类型的地方都可以用

@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {

    String value() default "hello";
}

把注解要做的事通过反射获取,获取功能又封装起来了,更加便捷

### Python类型注解的介绍 Python 是一种动态类型语言,在运行时才会确定变量的类型。类型注解(Type Annotations)是 Python 3.5 及以后版本引入的一项特性,它允许在代码中为变量、函数参数和返回值等添加类型提示信息。类型注解并不会影响代码的实际运行,它主要用于提高代码的可读性和可维护性,同时也能帮助 IDE 提供更好的代码提示和静态类型检查工具(如 `mypy`)发现潜在的类型错误。 ### Python类型注解的使用方法 #### 变量类型注解 变量类型注解通过在变量名后加上冒号和类型来实现。以下是一些示例: ```python # 整数类型注解 age: int = 25 # 字符串类型注解 name: str = "Alice" # 列表类型注解,列表元素为整数 numbers: list[int] = [1, 2, 3] # 字典类型注解,键为字符串,值为整数 scores: dict[str, int] = {"math": 90, "english": 85} ``` #### 函数参数和返回值类型注解 函数的参数和返回值也可以添加类型注解。参数类型注解在参数名后添加冒号和类型,返回值类型注解在函数定义的括号后使用箭头 `->` 加上类型。示例如下: ```python def add(a: int, b: int) -> int: return a + b result = add(3, 5) ``` #### 可选类型注解 当一个变量或参数可以是某种类型或者 `None` 时,可以使用 `typing.Optional` 进行注解。 ```python from typing import Optional def get_name() -> Optional[str]: # 模拟可能返回 None 的情况 import random if random.random() > 0.5: return "Bob" return None ``` #### 自定义类型注解 可以使用 `typing.TypeVar` 定义泛型类型变量,使用 `typing.NewType` 创建新的类型。 ```python from typing import TypeVar, NewType # 定义泛型类型变量 T = TypeVar('T') # 创建新的类型 UserId = NewType('UserId', int) def process_user_id(user_id: UserId): print(f"Processing user ID: {user_id}") new_user_id = UserId(123) process_user_id(new_user_id) ``` ### 相关知识 #### 类型检查工具 虽然类型注解本身不会影响代码的运行,但可以使用静态类型检查工具(如 `mypy`)来检查代码中的类型错误。安装 `mypy` 后,可以在命令行中运行 `mypy your_script.py` 来检查代码。 #### 类型注解与运行时 类型注解只是提示信息,不会在运行时进行强制类型检查。如果需要在运行时进行类型检查,可以使用 `isinstance` 函数。 ```python def divide(a: int, b: int) -> float: if not isinstance(a, int) or not isinstance(b, int): raise ValueError("Both arguments must be integers.") return a / b ``` #### 类型注解在类中的使用 在类中,也可以为属性和方法添加类型注解。 ```python class Person: def __init__(self, name: str, age: int): self.name: str = name self.age: int = age def get_info(self) -> str: return f"Name: {self.name}, Age: {self.age}" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值