注解详细解释+枚举

目录

1.1枚举简介

1.2、定义格式

实例

 1.3、枚举类的主要方法

实例 :

 1.4、实现接口的枚举类

实例

 1.5、注意事项

2.注解

2.1、简介 Java 注解(Annotation)

2.2、学习的重点

2.3、内置注解 

 2.4、元注解

    2.4.1、简介

   2.4.2、元注解有哪些?

2.5、自定义注解

   2.5.1、注解架构 

 2.5.2、定义格式

2.5.3、注意事项

案例


1.1枚举简介

枚举:可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。 用于定义有限数量的一组同类常量。例如:

       错误级别: 低、中、高、

       一年的四季: 春、夏、秋、冬

       商品的类型: 美妆、手机、电脑、男装、女装.

1.2、定义格式

Java 枚举类使用 enum 关键字来定义,各个常量使用逗号 , 来分割。例如:

    

enum Leavel{
 LOW, MEDIUM,HIGH;
}

实例

enum Level{
LOW,MEDIUM,HIGH;
}
public class Test
{
 public static void main(String[] args)
{
 Level l1 = Leve1.LOW;
  System.out.println(l1);
}

 1.3、枚举类的主要方法

实例 :

compareTo():假设a,b,c比较,a与b比结果是-1;a与c比结果是-2;b与a比结果是1.

注意:枚举中可以用equal比较也可以用Switch语句比较。

enum Leve1{
LOW,MEDIUM,HIGH;
}
public class Test
{
 public static void main(String[] args)
{
//比较顺序
  System.out.println( Leve1.LOW.compareTo(Leve1.HIGH));
  System.out.println( Leve1.LOW.compareTo(Leve1.MEDIUM);
  System.out.println( Leve1.HIGH.compareTo(Leve1.LOW));
//比较枚举常量
  System.out.println( Leve1.LOW.equals(Leve1.HIGH));
  System.out.println( Leve1.LOW.equals(Leve1.LOW));
//返回枚举名称
	 System.out.println( Leve1.LOW.name());
	 System.out.println( Leve1.LOW.toString());
//返回枚举常量序数,初始常量序数为0
	 System.out.println( Leve1.LOW.ordinal());
	  System.out.println( Leve1.HIGH.ordinal());
//返回带指定名称的枚举类型常量
	 Leve1 l = Enum.valueOf(Leve1.class,"HIGH");
	  System.out.println( l.name());
	 
}
//在Switch中实现枚举
//Leve1 e = Leve1.HIGH
	//{switch(e){
	//case LOW:
    //System.out.println("低级");
    //break;
	//	case HIGH:
    //System.out.println("高级");
    //  break;
 	//}
	//结果输出高级
	//}
	}

 1.4、实现接口的枚举类

所有的枚举都继承自java.lang.Enum抽象类。由于Java 不支持多继承,所以枚举对象不能再继承其他类。且每个枚举对象,都可以实现自己的抽象方法。

实例

interface Lshow{
 void show();
}

enum Leve1 implements Lshow{
LOW{
		
		public void show(){
			System.out.println("低级别");
		}
	},MEDIUM{
				
		public void show(){
			System.out.println("中级别");
		}
	},HIGH{
			
		public void show(){
			System.out.println("高级别");
		}
	};
}
public class Test
{
 public static void main(String[] args)
{
		Leve1.LOW.show();
		Leve1.HIGH.show(); 
}
}

 

 1.5、注意事项

  • 一旦定义了枚举,最好不要妄图修改里面的值,除非修改是必要的。
  • 枚举类默认继承的是java.lang.Enum类而不是Object类
  • 枚举类不能有子类,因为其枚举类默认被final修饰 只能有private构造方法
  • switch中使用枚举时,直接使用常量名,不用携带类名
  • 不能定义name属性,因为自带name属性
  • 不要为枚举类中的属性提供set方法,不符合枚举最初设计初衷。

2.注解

2.1、简介 Java 注解(Annotation)

又称 Java 标注,是 JDK5.0 引入的一种注释机制。 Java 语言中的类、方法、变量、参数和包等都可以被标注。和注释不同,Java 标注可以通过反射获取标 注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行 时可以获取到标注内容 。 当然它也支持自定义 Java 标注。

主要用于: 编译格式检查、反射中解析、 生成帮助文档、 跟踪代码依赖 等

2.2、学习的重点

理解 Annotation 的关键,是理解 Annotation 的语法和用法.

学习步骤:1.概念  2. 怎么使用内置注解  3. 怎么自定义注解  4. 反射中怎么获取注解内容

2.3、内置注解 

  • @override: 重写(只用在方法中,用于标识当前方法是重写父类(父接口)方法)

  •  @Deprecated:废弃 (如果调用了被标记为过时的方法,编译器在编译期进行提示警告。)

    应用场景:比如产品1.0发布后,后期需要升级2.0,升级后产品1.0不能直接废弃。因                              为废弃后会有好多用户可能不再使用该产品。所以用注释通知后,让用户

                    自主选择版本,废弃注释的方法有横线告知,但不代表不可以用,是建议不使用

  • @FunctionalInterface: 函数式接(标识一个匿名函数或函数式接口。该标记可有可无,标记                                                           上便于后期一眼看出他是函数接口)

  • @SuppressWarnings:抑制编译时的警告信息。 可以加在任何位置

1. @SuppressWarnings("unchecked") [^ 抑制单类型的警告]

2. @SuppressWarnings("unchecked","rawtypes") [^ 抑制多类型的警告]

3. @SuppressWarnings("all") [^ 抑制所有类型的警告]

当创建对象没有使用是字母是灰色是一种警告,加了注释后忽视了此警告 

 

 2.4、元注解

    2.4.1、简介

            作用在其他注解的注解

   2.4.2、元注解有哪些?

   @Retention - 标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可 以通过反射访问。

   @Documented - 标记这些注解是否包含在用户文档中 javadoc。 @Target - 标记这个注解应该是哪种 Java 成员。

   @Inherited - 标记这个注解是自动继承的。

                        1. 子类会继承父类使用的注解中被@Inherited修饰的注解

                        2. 接口继承关系中,子接口不会继承父接口中的任何注解,不管父接口中使                                用的注解有没有 被@Inherited修饰

                        3. 类实现接口时不会继承任何接口中定义的注解

 具体例子结合自定义注解展示

2.5、自定义注解

   2.5.1、注解架构 

          

 每 1 个 Annotation 对象,都会有唯一的 RetentionPolicy 属性;至于 ElementType 属性,则有 1~n 个。

  •  ElementType(注解的用途类型)

      "每 1 个 Annotation" 都与 "1~n 个 ElementType" 关联。当 Annotation 与某个 ElementType 关联 时,就意味着:Annotation有了某种用 

  •  RetentionPolicy(注解作用域策略)

         每 1 个 Annotation" 都与 "1 个 RetentionPolicy" 关联。

         a) 若 Annotation 的类型为 SOURCE,则意味着:Annotation 仅存在于编译器处理期间,编译器 处理完之后,该 Annotation 就没用了。 例如," @Override" 标志就是一个 Annotation。当它修 饰一个方法的时候,就意味着该方法覆盖父类的方法;并且在编译期间会进行语法检查!编译器处 理完后,"@Override" 就没有任何作用了。

          b) 若 Annotation 的类型为 CLASS,则意味着:编译器将 Annotation 存储于类对应的 .class 文件 中,它是 Annotation 的默认行为。

         c) 若 Annotation 的类型为 RUNTIME,则意味着:编译器将 Annotation 存储于 class 文件中,并 且可由JVM读入。(一般使用RUNTIME参数,因为RUNTIME包含上述两个参数)

 2.5.2、定义格式

@interface 自定义注解名{}

2.5.3、注意事项

1. 定义的注解,自动继承了java.lang,annotation.Annotation接口

2. 注解中的每一个方法,实际是声明的注解配置参数

            方法的名称就是 配置参数的名称 

             方法的返回值类型,就是配置参数的类型。只能是:基本类型/Class/String/enum

3. 可以通过default来声明参数的默认值

4. 如果只有一个参数成员,一般参数名为value

5. 注解元素必须要有值,我们定义注解元素时,经常使用空字符串、0作为默认值。

案例

package com.java;

import java.lang.annotation.*;
//将zhangsan 和1 传给注解的类
//@MyAnnotation(value ="zhangsan ",num = 1)
@MyAnnotation(num = 1)
public class Demo1 {
    public static void main(String[] args) {

    }

}
//描述注解
//是否在文档
@Documented
//给一个作用范围,比如这个注解可以作用在类上传参数:ElementType.TYPE。方法ElementType.METHOD
//现在可以再上边类或方法上上加@MyAnnotation
@Target({ElementType.TYPE,ElementType.METHOD})
//一个注解至少要对应一个Retention(持久的策略)
@Retention(RetentionPolicy.RUNTIME)
//可以继承
@Inherited
@interface  MyAnnotation{
//   写了方法,则上边@MyAnnotation注解需要传参,
   String value() default  "李四";//加上default是默认值上边@MyAnnotation(num = 1)可以不传value的值
   int num();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个 Java 示例代码,使用注解+反射+枚举实现字典方法: ```java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; @Retention(RetentionPolicy.RUNTIME) @interface DictionaryEntry { String key(); String value(); } enum Dictionary { FRUIT, COLOR, ANIMAL; } public class Main { private static Map<String, Map<String, String>> dictionaryMap = new HashMap<>(); public static void main(String[] args) { initDictionary(); String fruitName = "apple"; String fruitColor = getDictionaryValue(Dictionary.FRUIT, fruitName); System.out.println(fruitName + " is " + fruitColor); String colorName = "red"; String colorHex = getDictionaryValue(Dictionary.COLOR, colorName); System.out.println(colorName + " is " + colorHex); String animalName = "dog"; String animalSound = getDictionaryValue(Dictionary.ANIMAL, animalName); System.out.println(animalName + " says " + animalSound); } private static void initDictionary() { // Fruit dictionary Map<String, String> fruitMap = new HashMap<>(); fruitMap.put("apple", "red"); fruitMap.put("banana", "yellow"); fruitMap.put("orange", "orange"); dictionaryMap.put(Dictionary.FRUIT.name(), fruitMap); // Color dictionary Map<String, String> colorMap = new HashMap<>(); colorMap.put("red", "#FF0000"); colorMap.put("green", "#00FF00"); colorMap.put("blue", "#0000FF"); dictionaryMap.put(Dictionary.COLOR.name(), colorMap); // Animal dictionary Map<String, String> animalMap = new HashMap<>(); animalMap.put("dog", "woof"); animalMap.put("cat", "meow"); animalMap.put("bird", "tweet"); dictionaryMap.put(Dictionary.ANIMAL.name(), animalMap); } private static String getDictionaryValue(Dictionary dict, String key) { Map<String, String> dictMap = dictionaryMap.get(dict.name()); for (Map.Entry<String, String> entry : dictMap.entrySet()) { if (entry.getKey().equals(key)) { return entry.getValue(); } } return null; } static { for (Dictionary dict : Dictionary.values()) { Map<String, String> dictMap = new HashMap<>(); Class<?> dictClass; try { dictClass = Class.forName(dict.name()); } catch (ClassNotFoundException ex) { continue; } for (Field field : dictClass.getDeclaredFields()) { if (field.isAnnotationPresent(DictionaryEntry.class)) { DictionaryEntry entry = field.getAnnotation(DictionaryEntry.class); dictMap.put(entry.key(), entry.value()); } } dictionaryMap.put(dict.name(), dictMap); } } static class Fruit { @DictionaryEntry(key = "apple", value = "red") public static String APPLE; @DictionaryEntry(key = "banana", value = "yellow") public static String BANANA; @DictionaryEntry(key = "orange", value = "orange") public static String ORANGE; } static class Color { @DictionaryEntry(key = "red", value = "#FF0000") public static String RED; @DictionaryEntry(key = "green", value = "#00FF00") public static String GREEN; @DictionaryEntry(key = "blue", value = "#0000FF") public static String BLUE; } static class Animal { @DictionaryEntry(key = "dog", value = "woof") public static String DOG; @DictionaryEntry(key = "cat", value = "meow") public static String CAT; @DictionaryEntry(key = "bird", value = "tweet") public static String BIRD; } } ``` 这个例子,我们创建了一个枚举类型 `Dictionary`,表示三个不同的字典:`FRUIT`、`COLOR`、`ANIMAL`。我们使用注解 `@DictionaryEntry` 来标记每个字典的条目,然后使用反射初始化字典。 在 `initDictionary` 方法,我们创建了一个 `dictionaryMap`,包含了每个字典的名称和条目。我们使用反射枚举每个字典的条目,并将它们添加到 `dictionaryMap` 。 在 `getDictionaryValue` 方法,我们通过枚举类型 `Dictionary` 和键值 `key` 获取字典的值。我们首先从 `dictionaryMap` 获取对应的字典,然后遍历字典的条目,查找与给定键值匹配的条目并返回它的值。 注意,这个例子只是一个简单的演示,实际应用可能需要更复杂的字典结构和查询方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值