关于java:JAVA-基础之常用注解

45次阅读

共计 3857 个字符,预计需要花费 10 分钟才能阅读完成。

明天来讲讲 JAVA 种罕用的几种注解,比拟容易应用,也简略

@Override 查看笼罩办法是否正确
@Deprecated 将这个办法置为不举荐应用的办法
@SupperessWarnings 将某种正告提醒疏忽掉,能够放在类后面讲将整个类的这种正告疏忽,也能够放在办法头上,只疏忽这个办法的正告

public class Doer {
    @Deprecated
    void doItThisWay(){}
    void doItThisNewWay(){}
}

@SuppressWarnings("deprecation")
public class MyWorker {@SuppressWarnings("deprecation")
    void doSomeWork(){Doer d = new Doer();
        d.doItThisWay();}
    @SuppressWarnings("deprecation")
    void doDoubleWork(){Doer d1 = new Doer();
        Doer d2 = new Doer();
        d1.doItThisWay();
        d2.doItThisWay();}
}

自定义注解,通过 @interface 的形式定义,通过 @新注解名字来应用注解
其中 Target 指定该新定义的注解能够应用在哪个中央 @Target(ElementType.TYPE),@Target({ElementType.TYPE,ElementType.METHOD})等示意
另外 Retention 示意能够在何时能够获取到该新注解,RUNTIME 示意在运行时能够获取到(想要通过反射获取到必须应用这种 RUNTIME)
定义的变量能够设置为 default 值

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface WorkHandler {boolean useThreadPool() default true;
}

应用新注解,当下面的定义 default 时 true 时候,上面如果是(useThreadPool = true)则能够去掉,除非设置为 false 必填写
这样通过注解能够判断是否应用线程池

@WorkHandler(useThreadPool = true)
public class AccountWorker implements Runnable, TaskWorker {
    BankAccount ba;
    public void setTarget(Object target) {if(BankAccount.class.isInstance(target))
            ba = (BankAccount) target;
        else
            System.out.println("Not BankAccount");
    }
    public void doWork(){Thread t = new Thread(HighVolumeAccount.class.isInstance(ba) ? (HighVolumeAccount)ba: this);
        t.start();}

    @Override
    public void run() {
        char txType = 'w';
        int amt = 200;
        if(txType =='w')
            ba.withdrawal(amt);
        else
            ba.deposit(amt);
    }
}

执行办法:

com.example.demo.pluralsight.runtimetype.BankAccount acct2 = new com.example.demo.pluralsight.runtimetype.BankAccount("2");
startWork("com.example.demo.pluralsight.metadatawithannotations.AccountWorker",acct2);
Thread.sleep(100);
System.out.println("TaskAccountWorker:"+acct2.getBalance());

private static void startWork(String workerTypeName, Object workerTarget){
    try{Class<?> workerType = Class.forName(workerTypeName);
        AccountWorker worker= (AccountWorker)workerType.newInstance();
        worker.setTarget(workerTarget);
        ExecutorService pool = Executors.newFixedThreadPool(3);
        WorkHandler wh = workerType.getAnnotation(WorkHandler.class);
        if(wh == null)
            throw new Exception("WorkHandler is null");
        if(wh.useThreadPool())
            pool.submit(new Runnable() {
                @Override
                public void run() {worker.doWork();
                }
            });
        else
            worker.doWork();
        pool.shutdown();}catch (Exception e){e.printStackTrace();
    }
}

还能够简写,间接定义新注解的变量名称为 value,这样在类的后面写入的注解就能够间接写成 @WorkHandler(false)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface WorkHandler {boolean value() default true;
}

自定义注解的变量类型能够为,Primitive type,String,Enum,Annotation,Class<?>,同时也能够是这些类型的数组。
传入 class 的形式,这样又能够节俭一个传入参数

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ProcessedBy {Class<?> value();
}

@ProcessedBy(AccountWorkerProcessBy.class)
public class BankAccount {
    private String id;
    private int balance = 0;
    public BankAccount(String id){this.id = id;}
    public BankAccount(String id,int startBalance){
        this.id = id;
        balance = startBalance;
    }
    public String getId(){return id;}
    public synchronized int getBalance(){return balance;}
    public synchronized void deposit(int amount){balance += amount;}
    public synchronized void withdrawal(int amount){balance -= amount;}
}

public class AccountWorkerProcessBy implements Runnable {
    BankAccount ba;
    public void setTarget(Object target) {if(BankAccount.class.isInstance(target))
            ba = (BankAccount) target;
        else
            System.out.println("Not BankAccount");
    }
    public void doWork(){Thread t = new Thread(this);
        t.start();}

    @Override
    public void run() {
        char txType = 'w';
        int amt = 200;
        if(txType =='w')
            ba.withdrawal(amt);
        else
            ba.deposit(amt);
    }
}

执行办法:

BankAccount acct3 = new BankAccount("3");
startWorkSelfContained(acct3);
System.out.println("startWorkSelfContained:"+acct3.getBalance());

private static void startWorkSelfContained(Object workerTarget) throws Exception{Class<?> targetType = workerTarget.getClass();
    ProcessedBy pb = targetType.getAnnotation(ProcessedBy.class);
    Class<?> workerType = pb.value();
    AccountWorkerProcessBy worker = (AccountWorkerProcessBy) workerType.newInstance();
    worker.setTarget(workerTarget);
    worker.doWork();}
输入
startWorkSelfContained:-200

正文完
 0