热门搜索 :
考研考公
您的当前位置:首页正文

java虚拟机:06_注解

来源:东饰资讯网

一、写注解

注解,是对代码的特殊注释,跟//注释功能一样
注释太过于随意,只能人去读,程序没法理解
注解,先要定义声明,再按照固定格式书写,程序就能够识别和理解

注解 注释
注解的内容,要先定义 注释的内容,随便写
注解按规定格式写 注释,随便写
注解可以被程序和人理解 注释,只能被人理解
注解可以限制使用的地方 注释可以在类的任何地方书写
注解可以在源代码、class文件、内存存在 注释只在java源文件里面存在,编译后就没了

二、读注解

//这个类是用来封装表数据,对应的表示student
@Table(name="student")
public class Student {
    //这个属性,对应student表的sname
    @Column(name="sname")
    private String name;
    //这个属性,对应student表的sno
    @Column(name="sno")
    private String id;

对比html
在html文件里面,写一句话:“这是一个测试界面”
<title>这是一个测试界面</title>
<body>这是一个测试界面</body>
<input type="button" value="这是一个测试界面">

标签处理器:浏览器

java代码:
写一个java类,类名含义、字段含义、方法含义,不加备注,不知道该怎么处理

抽象界面逻辑

## 组合子
驱动:driver(固定,写父类)
元素:webelement(写子类)
事件:click、clean+sendkeys、switchToWindow(固定,写父类)

## 规则
1.by+描述=元素(by和描述是变化的,子类写;处理是固定的,写公共类)
2.元素+事件=操作
3. 操作+操作=功能
4. 页面+页面=业务流程

一、定义注解

  1. @interface:注解的类型,取自定义注解的名字
  2. 使用jdk的基础注解,描述自定义注解的属性
  3. 定义注解的可选参数,和获取参数的方法,以及参数默认值
package com.guoyasoft.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*
 * 1. 允许子类继承父类的注解
 */
@Inherited
/*
 * 2. 该注解可以用在什么元素上:Field表示字段;可以指定多个作用对象,如可以同时用到类名、字段和方法上,多个用数组表示{,}
 */
@Target(ElementType.FIELD)
/*
 * 3. 注解保留到哪个阶段:源代码开发SOURCE、编译期(CLASS)、运行期(RUNTIME)
 */
@Retention(RetentionPolicy.RUNTIME)
/*
 * 4. 注解的类型:@interface,java的其它几种类型为:class、abstract class、interface
 */
public @interface FindBy {
    /*
     *5. 定义获取参数的方法,定义后,注解可以带同名参数,并通过注解的该方法获取参数的值 
     *
     *如:使用注解
     *@FindBy(xpath="")
     *WebElement element;
     *
     *获取注解的值
     *Annotation a=field.getAnnotation(FindBy.class);
     *String value=a.xpath();
     */
    String id() default "";
    String name() default "";
    String xpath() default "";
    String linkText() default "";
    String partitialLinkText() default "";  
}

二、使用注解

package 

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class BrowserEngine {
    public static WebDriver startupChrome() {
        System.setProperty("webdriver.chrome.driver",
                "src/main/resources/selenium/driver/chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        WebDriver driver = new ChromeDriver(options);
        return driver;
    }
    
    public static void shutdownChrome(WebDriver driver) {  
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        System.out.println( "Closing browser...");  
        driver.quit();  
    } 

}

package 

import java.util.Set;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class BasePage {
    //公共属性
    public WebDriver driver;
    public String pageTitle;
    public String pageUrl;
    
    /*
     * 构造方法
     */
    protected BasePage(WebDriver driver) {
        this.driver = driver;
        this.pageUrl=driver.getCurrentUrl();
        this.pageTitle=driver.getTitle();
    }

    /*
     * 在文本框内输入字符
     */
    protected void text(WebElement element, String text) {
        try {
            if (element.isEnabled()) {
                element.clear();
                System.out.println("Clean the value if any in "
                        + element.toString() + ".");
                element.sendKeys(text);
                System.out.println("Type value is: " + text + ".");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 点击元素,这里指点击鼠标左键
     */
    protected void click(WebElement element) {

        try {
            if (element.isEnabled()) {
                element.click();
                System.out.println("Element: " + element.toString()
                        + " was clicked.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 在文本输入框执行清除操作
     */
    protected void clean(WebElement element) {

        try {
            if (element.isEnabled()) {
                element.clear();
                System.out.println("Element " + element.toString()
                        + " was cleaned.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
     * 判断一个页面元素是否显示在当前页面
     */
    protected void verifyElementIsPresent(WebElement element) {

        try {
            if (element.isDisplayed()) {
                System.out.println("This Element " + element.toString().trim()
                        + " is present.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 获取页面的标题
     */
    protected String getCurrentPageTitle() {

        pageTitle = driver.getTitle();
        System.out.println("Current page title is " + pageTitle);
        return pageTitle;
    }

    /*
     * 获取页面的url
     */
    protected String getCurrentPageUrl() {

        pageUrl = driver.getCurrentUrl();
        System.out.println("Current page title is " + pageUrl);
        return pageUrl;
    }

    public void switchToNextWindow() {

        String currentWindow = driver.getWindowHandle();// 获取当前窗口句柄
        Set<String> handles = driver.getWindowHandles();// 获取所有窗口句柄
        System.out.println("当前窗口数量: " + handles.size());
        for (String s : handles) {
            if (currentWindow.endsWith(s)) {
                continue;
            } else {
                try {
                    WebDriver window = driver.switchTo().window(s);// 切换到新窗口
                    System.out
                            .println("new page title is " + window.getTitle());
                    break;
                } catch (Exception e) {
                    System.out.println("法切换到新打开窗口" + e.getMessage());

                }
            }
        }
    }

    public void switchToTitleWindow(String windowTitle) {
        // 将页面上所有的windowshandle放在入set集合当中
        String currentHandle = driver.getWindowHandle();
        Set<String> handles = driver.getWindowHandles();
        for (String s : handles) {
            driver.switchTo().window(s);
            // 判断title是否和handles当前的窗口相同
            if (driver.getTitle().contains(windowTitle)) {
                break;// 如果找到当前窗口就停止查找
            }
        }
    }
    
    public void sleep(int time){  
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        System.out.println("Wait for "+time+" seconds.");  
    }
}

package com.guoyasoft.pages.jd;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import 


public class HomePage extends BasePage{
    //搜索输入框  
    @FindBy (id="key")  
    WebElement search_inputBox; 
    
    //搜索提交按钮  
    @FindBy (xpath="//*[@id='search']/div/div[2]/button")  
    WebElement search_submitBtn;  
    
    
    public HomePage(WebDriver driver) {
        super(driver);
    }
    
    /*  
     * 搜索框输入关键字,点击搜索  
     */  
    public void searchWithKeyword(String keyword){  
        text(search_inputBox, keyword);  
        click(search_submitBtn); 
    }  

}

三、注解处理器

package com.guoyasoft.testAnotation.annotation.webelement.annotation;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.guoyasoft.recode.pages.jd.HomePage;


public class FindBySvc {

    public static HomePage initPage(WebDriver driver, Class<HomePage> pageClass)
            throws Exception {
        driver.manage().timeouts().pageLoadTimeout(3000, TimeUnit.MILLISECONDS);
        Constructor<HomePage> constructor = pageClass.getConstructor(WebDriver.class);
        HomePage page = constructor.newInstance(driver);

        List<Field> fields = getAllFields(pageClass);
        for (Field f : fields) {
            FindBy findBy = f.getAnnotation(FindBy.class);
            if (findBy != null) {
                if (WebElement.class.getName().equals(f.getType().getName())) {
                    WebElement element = getElement(driver, findBy);
                    f.set(page, element);
                }
            }
        }
        return page;
    }

    private static WebElement getElement(WebDriver driver, FindBy findBy) {
        WebElement element = null;
        if (!"".equals(findBy.xpath())) {
            element = driver.findElement(By.xpath(findBy.xpath()));
        } else if (!"".equals(findBy.id())) {
            element = driver.findElement(By.id(findBy.id()));
        } else if (!"".equals(findBy.name())) {
            element = driver.findElement(By.name(findBy.name()));
        }
        return element;
    }

    public static List<Field> getAllFields(Class page) {
        List<Field> list = new ArrayList<>();
        Class tempClass = page;
        while (tempClass != null) {// 当父类为null的时候说明到达了最上层的父类(Object类).
            list.addAll(Arrays.asList(tempClass.getDeclaredFields()));
            tempClass = tempClass.getSuperclass(); // 得到父类,然后赋给自己
        }
        return list;
    }
}

四、使用注解处理器

package com.guoyasoft.testAnotation.annotation.webelement;

import java.util.Properties;

import org.openqa.selenium.WebDriver;

import com.guoyasoft.recode.pages.jd.HomePage;
import 
import com.guoyasoft.testAnotation.annotation.webelement.annotation.FindBySvc;
import com.guoyasoft.testAnotation.annotation.webelement.pages.BasePage;

public class Test {
    public static void main(String[] args) throws Exception {
        WebDriver driver=BrowserEngine.startChrome();
        HomePage homePage=FindBySvc.initPage(driver, HomePage.class);
        homePage.searchWithKeyword("iphone7");
    }
}

五、使用泛型优化注解处理器

package com.guoyasoft.testAnotation.annotation.webelement.annotation;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class FindBySvc {

    public static <T> T initPage(WebDriver driver, Class<T> pageClass)
            throws Exception {
        driver.manage().timeouts().pageLoadTimeout(3000, TimeUnit.MILLISECONDS);
        Constructor<T> constructor = pageClass.getConstructor(WebDriver.class);
        T page = constructor.newInstance(driver);

        List<Field> fields = getAllFields(pageClass);
        for (Field f : fields) {
            FindBy findBy = f.getAnnotation(FindBy.class);
            if (findBy != null) {
                if (WebElement.class.getName().equals(f.getType().getName())) {
                    WebElement element = getElement(driver, findBy);
                    f.set(page, element);
                }
            }
        }
        return page;
    }

    private static WebElement getElement(WebDriver driver, FindBy findBy) {
        WebElement element = null;
        if (!"".equals(findBy.xpath())) {
            element = driver.findElement(By.xpath(findBy.xpath()));
        } else if (!"".equals(findBy.id())) {
            element = driver.findElement(By.id(findBy.id()));
        } else if (!"".equals(findBy.name())) {
            element = driver.findElement(By.name(findBy.name()));
        }
        return element;
    }

    public static List<Field> getAllFields(Class page) {
        List<Field> list = new ArrayList<>();
        Class tempClass = page;
        while (tempClass != null) {// 当父类为null的时候说明到达了最上层的父类(Object类).
            list.addAll(Arrays.asList(tempClass.getDeclaredFields()));
            tempClass = tempClass.getSuperclass(); // 得到父类,然后赋给自己
        }
        return list;
    }
}

注解作用位置target

作用位置 代码
ElementType.TYPE
构造器
字段
方法
参数
注解类型
Top