提交 c5caefa2 编写于 作者: W wizardforcel

2020-06-24 15:38:41

上级 56021129
......@@ -53,6 +53,103 @@ Assert.assertNotEquals("WebDriver Demo Website", pageTitle);
System.out.println("Assert not equals failed");
```
![Assert condition failed](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20720%20340'%3E%3C/svg%3E)
![Assert condition failed](img/9272cef7d4d831fd5ed1b3ae54bbd374.png)
<noscript><img alt="Assert condition failed" class="alignnone size-full wp-image-14150" height="340" src="img/9272cef7d4d831fd5ed1b3ae54bbd374.png" width="720"/><p>上图中的控制台显示<code>assertEquals</code>条件成功,因此将打印检查后的语句,“<strong>声明等于通过。 </strong>”,而<code>assertNotEquals</code>条件失败,因此将不执行此检查之后的行。 打印语句“<strong>声明不等于失败</strong>”不会打印到控制台。</p><h3>情况 3:尽管 assertNotEquals 条件失败,但通过测试用例</h3><p>要仅验证实际值和预期值是否不相等,请使用<code>try-catch</code>块。</p><p><strong>Code snippet</strong></p><pre><code class="language-java">//Verify title not equal using try-catch block try { // Making the test fail Assert.assertNotEquals("WebDriver Demo Website", pageTitle); } catch(Error e){ // Following lines will be printed when the assert condition fails System.out.println("Assert not equals failed. But test execution is not aborted."); System.out.println("Error message: " + e.toString()); }</code></pre><p>即使<code>assertNotEquals</code>条件失败,catch 块中的语句也将被执行,并且错误消息将被打印到控制台。</p><p><img alt="Verify condition fails" class="alignnone size-full wp-image-14149" data-lazy-sizes="(max-width: 825px) 100vw, 825px" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1.jpg" data-lazy-srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1.jpg 825w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-300x124.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-768x318.jpg 768w" height="342" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20825%20342'%3E%3C/svg%3E" width="825"/></p><noscript><img alt="Verify condition fails" class="alignnone size-full wp-image-14149" height="342" sizes="(max-width: 825px) 100vw, 825px" src="img/d09793dee60556d778b6b7f310560194.png" srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1.jpg 825w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-300x124.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/12/2_VerifyFailure-1-768x318.jpg 768w" width="825"/><p>如图所示,测试用例执行成功,并且错误被打印到控制台。</p><h2>完整的代码</h2><pre><code class="language-java">import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class AssertAndVerify { // Declaring variables private WebDriver driver; private String baseUrl; @Before public void setUp() throws Exception { // Selenium version 3 beta releases require system property set up System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\" + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe"); // Create a new instance for the class FirefoxDriver // that implements WebDriver interface driver = new FirefoxDriver(); // Implicit wait for 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // Assign the URL to be invoked to a String variable baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/"; } @Test public void testPageTitle() throws Exception { // Open baseUrl in Firefox browser window driver.get(baseUrl); // Get the page title String pageTitle = driver.getTitle(); // Print the title to console System.out.println("The actual title is: " + pageTitle); // Check if actual and expected values are equal Assert.assertEquals("WebDriver Demo Website", pageTitle); // Printing success message System.out.println("Assert equals passed."); // Making the test fail //Assert.assertNotEquals("WebDriver Demo Website", pageTitle); // Following lines will not be executed as above assert condition fails //System.out.println("Assert not equals failed"); //Verify title not equal using try-catch block try { // Making the test fail Assert.assertNotEquals("WebDriver Demo Website", pageTitle); } catch(Error e){ // Following lines will be printed when the assert condition fails System.out.println("Assert not equals failed. But test execution is not aborted."); System.out.println("Error message: " + e.toString()); } } // End of @Test @After public void tearDown() throws Exception { // Close the Firefox browser driver.close(); } }</code></pre><p>所有代码文件都放置在<a href="https://github.com/JBTAdmin/Selenium/tree/master/WebDriver"> GitHub 存储库</a>中,以方便访问。 您可以为存储库加注星标和分支以方便使用。 请仔细阅读“README.md”文件以获取明确说明。</p><p>总结了断言和验证的这一部分。 祝你有美好的一天!</p><div class="sticky-nav" style="font-size: 15px;"><div class="sticky-nav-image"></div><div class="sticky-nav-holder"><div class="sticky-nav_item"><h6 class="heading-sm">下一篇文章</h6></div><h5 class="sticky-nav_heading " style="font-size: 15px;"><a href="https://javabeginnerstutorial.com/selenium/9s-webdriver-handling-text-boxes-images/" title="9s. WebDriver – Handling text boxes and images"> 9 秒。 WebDriver – 处理文本框和图像</a></h5></div></div> </body> </html></noscript>
\ No newline at end of file
上图中的控制台显示`assertEquals`条件成功,因此将打印检查后的语句,“**断言等于通过**”,而`assertNotEquals`条件失败,因此将不执行此检查之后的行。 打印语句“**断言不等于失败**”不会打印到控制台。
### 情况 3:尽管`assertNotEquals`条件失败,但通过测试用例
要仅验证实际值和预期值是否不相等,请使用`try-catch`块。
**代码块**
```java
//Verify title not equal using try-catch block
try {
// Making the test fail
Assert.assertNotEquals("WebDriver Demo Website", pageTitle);
} catch(Error e){
// Following lines will be printed when the assert condition fails
System.out.println("Assert not equals failed. But test execution is not aborted.");
System.out.println("Error message: " + e.toString());
}
```
即使`assertNotEquals`条件失败,`catch`块中的语句也将被执行,并且错误消息将被打印到控制台。
![Verify condition fails](img/d09793dee60556d778b6b7f310560194.png)
如图所示,测试用例执行成功,并且错误被打印到控制台。
## 完整的代码
```java
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AssertAndVerify {
// Declaring variables
private WebDriver driver;
private String baseUrl;
@Before
public void setUp() throws Exception {
// Selenium version 3 beta releases require system property set up
System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
+ "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
// Create a new instance for the class FirefoxDriver
// that implements WebDriver interface
driver = new FirefoxDriver();
// Implicit wait for 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Assign the URL to be invoked to a String variable
baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
}
@Test
public void testPageTitle() throws Exception {
// Open baseUrl in Firefox browser window
driver.get(baseUrl);
// Get the page title
String pageTitle = driver.getTitle();
// Print the title to console
System.out.println("The actual title is: " + pageTitle);
// Check if actual and expected values are equal
Assert.assertEquals("WebDriver Demo Website", pageTitle);
// Printing success message
System.out.println("Assert equals passed.");
// Making the test fail
//Assert.assertNotEquals("WebDriver Demo Website", pageTitle);
// Following lines will not be executed as above assert condition fails
//System.out.println("Assert not equals failed");
//Verify title not equal using try-catch block
try {
// Making the test fail
Assert.assertNotEquals("WebDriver Demo Website", pageTitle);
} catch(Error e){
// Following lines will be printed when the assert condition fails
System.out.println("Assert not equals failed. But test execution is not aborted.");
System.out.println("Error message: " + e.toString());
}
} // End of @Test
@After
public void tearDown() throws Exception {
// Close the Firefox browser
driver.close();
}
}
```
所有代码文件都放置在 [GitHub 存储库](https://github.com/JBTAdmin/Selenium/tree/master/WebDriver)中,以方便访问。 您可以为存储库加注星标和分支以方便使用。 请仔细阅读“`README.md`”文件以获取明确说明。
总结了断言和验证的这一部分。 祝你有美好的一天!
......@@ -30,6 +30,223 @@ JavaScript code:
window.confirm("Click 'OK' or 'Cancel'.");
```
![Confirm Box](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20473%20231'%3E%3C/svg%3E)
![Confirm Box](img/eb42ced4a961c35a4e35d860b23ca096.png)
<noscript><img alt="Confirm Box" class="alignnone size-full wp-image-12511" height="231" src="img/eb42ced4a961c35a4e35d860b23ca096.png" width="473"/><h2><strong> 3.提示框</strong></h2><p>在我们希望用户输入值的情况下,将使用提示框。 与其他警报框类似,用户必须单击“确定”或“取消”按钮才能继续操作。 提示框在单击“确定”时返回输入值,而在单击“取消”时返回空值。</p><p> JavaScript 代码: <span class="ezoic-adpicker-ad" id="ezoic-pub-ad-placeholder-124"> </span> <span class="ezoic-ad box-4 adtester-container adtester-container-124" data-ez-name="javabeginnerstutorial_com-box-4" style="display:block !important;float:none;margin-bottom:2px !important;margin-left:0px !important;margin-right:0px !important;margin-top:2px !important;min-height:110px;min-width:728px;text-align:center !important;"> <span class="ezoic-ad ezoic-adl" ezah="90" ezaw="728" id="div-gpt-ad-javabeginnerstutorial_com-box-4-0" style="position:relative;z-index:0;display:inline-block;min-height:90px;min-width:728px;"> </span> </span></p><pre><code class="language-javascript">window.prompt("Which Selenium Tool do you like the most?","e.g. Selenium IDE");</code></pre><p><img alt="Prompt Box" class="alignnone size-full wp-image-12508" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2017/08/PromptBox-1.jpg" height="231" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20478%20231'%3E%3C/svg%3E" width="478"/></p><noscript><img alt="Prompt Box" class="alignnone size-full wp-image-12508" height="231" src="img/f245ded24a74c295f8cd11219e80647a.png" width="478"/><p>希望您现在对基于 Web 的弹出窗口的不同类型有清楚的了解。</p><h2><strong>处理弹出框:</strong></h2><p>Selenium WebDriver 尚未提供任何处理这些弹出框的方法。 你相信我刚才说的吗?</p><p>哈! 我知道没有骗你的! WebDriver 总是对我们所有问题都有答案。 <strong>警报接口</strong>随<strong> org.openqa.selenium.Alert </strong> <em>包</em>一起提供!</p><p>经常使用的一些最有用的方法是:</p><h3>1\. WebDriver switchTo()</h3><p>这是用于从主窗口切换到弹出窗口或显示的警报的方法。</p><pre><code class="language-java">driver.switchTo().alert();</code></pre><h3>2.无效 accept()</h3><p>此方法用于接受警报。 点击“确定”按钮。</p><pre><code class="language-java">driver.switchTo().alert().accept();</code></pre><h3>3.无效 dismiss()</h3><p>此方法用于消除警报。 点击“取消”按钮。</p><pre><code class="language-java">driver.switchTo().alert().dismiss();</code></pre><h3>4.字符串 getText()</h3><p>要使文本显示在弹出框中,请使用此方法,它将文本作为字符串返回。</p><pre><code class="language-java">driver.switchTo().alert().getText();</code></pre><h3>5\. void sendKeys(String textToSend)</h3><p>此方法用于在显示的弹出框中(通常是提示框)输入特定的 String。</p><pre><code class="language-java">driver.switchTo().alert().sendKeys(“sampleText”);</code></pre><h2><strong> 场景 </strong></h2><p>让我们来看一个实现这些方法的测试用例,以更深入地了解这些概念,</p><ol><li>打开 Firefox 浏览器</li><li>导航到<a href="https://chandanachaitanya.github.io/selenium-practice-site/">演示站点</a></li><li>使用 ID 找到“警告框”按钮</li><li>单击按钮以弹出警报框</li><li>获取警报弹出窗口的显示文本并将其打印到控制台</li><li>接受警报弹出窗口</li><li>使用 ID 找到“确认框”按钮</li><li>单击按钮以确认框弹出</li><li>将警报消息打印到控制台</li><li>关闭确认弹出窗口</li><li>使用 XPath 找到“提示框”按钮</li><li>单击按钮,弹出提示框</li><li>获取提示框消息并将其显示到控制台</li><li>接受 promt 弹出窗口</li><li>验证 Eclipse IDE 控制台输出屏幕和 JUnit 窗格是否成功</li></ol><p>此方案的 JUnit 代码是,</p><pre><code class="language-java">package com.blog.junitTests; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class PopupBoxes { // Declaring variables private WebDriver driver; private String baseUrl; @Before public void setUp() throws Exception { // Selenium version 3 beta releases require system property set up System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\" + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe"); // Create a new instance for the class FirefoxDriver // that implements WebDriver interface driver = new FirefoxDriver(); // Implicit wait for 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // Assign the URL to be invoked to a String variable baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/"; } @Test public void testPageTitle() throws Exception { // Open baseUrl in Firefox browser window driver.get(baseUrl); // Locate 'Alert Box' button using id WebElement alertBoxBtn = driver.findElement(By.id("alertBox")); // Click the button for alert box popup alertBoxBtn.click(); // Switch the control to 'Alert Box' popup Alert alertPopUp = driver.switchTo().alert(); // Print the alert message to console System.out.println("Alert Box message: " + alertPopUp.getText()); // Accept the alert popup alertPopUp.accept(); Thread.sleep(5000); // Locate 'Confirm Box' button using id WebElement confirmBoxBtn = driver.findElement(By.id("confirmBox")); // Click the button for confirm box popup confirmBoxBtn.click(); // Switch control to 'Confirm Box' popup Alert confirmPopUp = driver.switchTo().alert(); // Dismiss the popup confirmPopUp.dismiss(); System.out.println("Confirm box popup dismissed!"); Thread.sleep(5000); // Locate 'Prompt Box' button using XPath WebElement promptBoxBtn = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/button")); // Click the button for prompt box popup promptBoxBtn.click(); // Switch control to 'Prompt Box' popup Alert promptPopUp = driver.switchTo().alert(); // Display the prompt message to console System.out.println(promptPopUp.getText()); // Click 'OK' promptPopUp.accept(); } //End of @Test @After public void tearDown() throws Exception { // Close the Firefox browser driver.close(); } }</code></pre><p><em>代码说明:</em></p><ol><li>为了实例化一个弹出框,我们将必须导入“<strong> import </strong> openqa.selenium.Alert package”。</li></ol><p>键入上述代码后,“Alert”一词下方会出现一条弯曲的线。 悬停时,蚀将建议所有可能的快速修复。 单击建议导入“警报”包的第一个修补程序。</p><p><img alt="Import alert package" class="alignnone size-full wp-image-12510" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2017/08/AlertImport-1.jpg" height="197" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20393%20197'%3E%3C/svg%3E" width="393"/></p><noscript><img alt="Import alert package" class="alignnone size-full wp-image-12510" height="197" src="img/8c7bdadd655552e5973edd3979ae7a74.png" width="393"/><pre><code class="language-java">// Switch the control to 'Alert Box' popup Alert alertPopUp = driver.switchTo().alert();</code></pre><p>该包指定了 Alert 界面,该界面用于处理基于 Web 的弹出框。</p><p>“alertPopUp”是为引用显示的弹出窗口而创建的新实例变量。</p><p>2.要将控件从主窗口切换到弹出窗口,</p><pre><code class="language-java">driver.switchTo().alert();</code></pre><p>3.要使文本显示在弹出框中,请在引用所生成警报的实例变量上使用 getText()方法。</p><pre><code class="language-java">// Print the alert message to console System.out.println("Alert Box message: " + alertPopUp.getText());</code></pre><p>4.要接受警报,请使用 accept()方法。</p><pre><code class="language-java">// Accept the alert popup alertPopUp.accept();</code></pre><p>5.要关闭警报,请使用 dismiss()方法。</p><pre><code class="language-java">// Dismiss the popup confirmPopUp.dismiss();</code></pre><p><em>执行结果:</em></p><p>在 JUnit 窗口中,绿色条显示测试用例已成功执行。 控制台窗口显示没有任何错误。 它还按预期显示所有打印的消息。</p><p><img alt="Alert Eclipse output" class="alignnone size-full wp-image-12507" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2017/08/EclipseOutput-1.jpg" height="342" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20677%20342'%3E%3C/svg%3E" width="677"/></p><noscript><img alt="Alert Eclipse output" class="alignnone size-full wp-image-12507" height="342" src="img/5f21cb9c556c1522fd9bcdb900117ab4.png" width="677"/><p>是时候练习了,我很快会在另一篇文章中见。 祝你有美好的一天!</p><p> </p><p> </p><div class="sticky-nav" style="font-size: 15px;"><div class="sticky-nav-image"></div><div class="sticky-nav-holder"><div class="sticky-nav_item"><h6 class="heading-sm">下一篇文章</h6></div><h5 class="sticky-nav_heading " style="font-size: 15px;"><a href="https://javabeginnerstutorial.com/selenium/9y-webdriver-handling-multiple-windows/" title="9y. WebDriver – Handling multiple windows"> 9 岁。 WebDriver – 处理多个窗口</a></h5></div></div> </body> </html></noscript>
\ No newline at end of file
## **3\. 提示框**
在我们希望用户输入值的情况下,将使用提示框。 与其他警报框类似,用户必须单击“确定”或“取消”按钮才能继续操作。 提示框在单击“确定”时返回输入值,而在单击“取消”时返回空值。
JavaScript 代码:
```javascript
window.prompt("Which Selenium Tool do you like the most?","e.g. Selenium IDE");
```
![Prompt Box](img/f245ded24a74c295f8cd11219e80647a.png)
希望您现在对基于 Web 的弹出窗口的不同类型有清楚的了解。
## **处理弹出框:**
Selenium WebDriver 尚未提供任何处理这些弹出框的方法。 你相信我刚才说的吗?
哈! 我知道没有骗你的! WebDriver 总是对我们所有问题都有答案。 **警报接口**`org.openqa.selenium.Alert`*包*一起提供!
经常使用的一些最有用的方法是:
### 1\. `WebDriver switchTo()`
这是用于从主窗口切换到弹出窗口或显示的警报的方法。
```java
driver.switchTo().alert();
```
### 2\. `void accept()`
此方法用于接受警报。 点击“确定”按钮。
```java
driver.switchTo().alert().accept();
```
### 3\. `void dismiss()`
此方法用于消除警报。 点击“取消”按钮。
```java
driver.switchTo().alert().dismiss();
```
### 4\. `字符串 getText()`
要使文本显示在弹出框中,请使用此方法,它将文本作为字符串返回。
```java
driver.switchTo().alert().getText();
```
### 5\. `void sendKeys(String textToSend)`
此方法用于在显示的弹出框中(通常是提示框)输入特定的`String`
```java
driver.switchTo().alert().sendKeys(sampleText);
```
## **场景**
让我们来看一个实现这些方法的测试用例,以更深入地了解这些概念,
1. 打开 Firefox 浏览器
2. 导航到[演示站点](https://chandanachaitanya.github.io/selenium-practice-site/)
3. 使用 ID 找到“警告框”按钮
4. 单击按钮以弹出警报框
5. 获取警报弹出窗口的显示文本并将其打印到控制台
6. 接受警报弹出窗口
7. 使用 ID 找到“确认框”按钮
8. 单击按钮以确认框弹出
9. 将警报消息打印到控制台
10. 关闭确认弹出窗口
11. 使用 XPath 找到“提示框”按钮
12. 单击按钮,弹出提示框
13. 获取提示框消息并将其显示到控制台
14. 接受提示弹出窗口
15. 验证 Eclipse IDE 控制台输出屏幕和 JUnit 窗格是否成功
此方案的 JUnit 代码是,
```java
package com.blog.junitTests;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PopupBoxes {
// Declaring variables
private WebDriver driver;
private String baseUrl;
@Before
public void setUp() throws Exception {
// Selenium version 3 beta releases require system property set up
System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
+ "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
// Create a new instance for the class FirefoxDriver
// that implements WebDriver interface
driver = new FirefoxDriver();
// Implicit wait for 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Assign the URL to be invoked to a String variable
baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
}
@Test
public void testPageTitle() throws Exception {
// Open baseUrl in Firefox browser window
driver.get(baseUrl);
// Locate 'Alert Box' button using id
WebElement alertBoxBtn = driver.findElement(By.id("alertBox"));
// Click the button for alert box popup
alertBoxBtn.click();
// Switch the control to 'Alert Box' popup
Alert alertPopUp = driver.switchTo().alert();
// Print the alert message to console
System.out.println("Alert Box message: " + alertPopUp.getText());
// Accept the alert popup
alertPopUp.accept();
Thread.sleep(5000);
// Locate 'Confirm Box' button using id
WebElement confirmBoxBtn = driver.findElement(By.id("confirmBox"));
// Click the button for confirm box popup
confirmBoxBtn.click();
// Switch control to 'Confirm Box' popup
Alert confirmPopUp = driver.switchTo().alert();
// Dismiss the popup
confirmPopUp.dismiss();
System.out.println("Confirm box popup dismissed!");
Thread.sleep(5000);
// Locate 'Prompt Box' button using XPath
WebElement promptBoxBtn = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/button"));
// Click the button for prompt box popup
promptBoxBtn.click();
// Switch control to 'Prompt Box' popup
Alert promptPopUp = driver.switchTo().alert();
// Display the prompt message to console
System.out.println(promptPopUp.getText());
// Click 'OK'
promptPopUp.accept();
} //End of @Test
@After
public void tearDown() throws Exception {
// Close the Firefox browser
driver.close();
}
}
```
*代码说明:*
1\. 为了实例化一个弹出框,我们将必须导入`import openqa.selenium.Alert`包。
键入上述代码后,“`Alert`”一词下方会出现一条弯曲的线。 悬停时,蚀将建议所有可能的快速修复。 单击建议导入“警报”包的第一个修补程序。
![Import alert package](img/8c7bdadd655552e5973edd3979ae7a74.png)
```java
// Switch the control to 'Alert Box' popup
Alert alertPopUp = driver.switchTo().alert();
```
该包指定了`Alert`界面,该界面用于处理基于 Web 的弹出框。
`alertPopUp`”是为引用显示的弹出窗口而创建的新实例变量。
2\. 要将控件从主窗口切换到弹出窗口,
```java
driver.switchTo().alert();
```
3\. 要使文本显示在弹出框中,请在引用所生成警报的实例变量上使用`getText()`方法。
```java
// Print the alert message to console
System.out.println("Alert Box message: " + alertPopUp.getText());
```
4\. 要接受警报,请使用`accept()`方法。
```java
// Accept the alert popup
alertPopUp.accept();
```
5\. 要关闭警报,请使用`dismiss()`方法。
```java
// Dismiss the popup
confirmPopUp.dismiss();
```
*执行结果:*
在 JUnit 窗口中,绿色条显示测试用例已成功执行。 控制台窗口显示没有任何错误。 它还按预期显示所有打印的消息。
![Alert Eclipse output](img/5f21cb9c556c1522fd9bcdb900117ab4.png)
是时候练习了,我很快会在另一篇文章中见。 祝你有美好的一天!
......@@ -12,4 +12,143 @@
![POI download link](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20859%20433'%3E%3C/svg%3E)
<noscript><img alt="POI download link" class="alignnone size-full wp-image-13586" height="433" sizes="(max-width: 859px) 100vw, 859px" src="img/66dde6eb58d06604bfe3993478f8010c.png" srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/07/1_DownloadLink.jpg 859w, https://javabeginnerstutorial.com/wp-content/uploads/2018/07/1_DownloadLink-300x151.jpg 300w, https://javabeginnerstutorial.com/wp-content/uploads/2018/07/1_DownloadLink-768x387.jpg 768w" width="859"/><h2><strong>步骤 2:</strong></h2><p>将这些 JAR 添加到我们的项目构建路径中。 确保选择“poi-x.xx”,“ooxml-lib”和“lib”文件夹下的所有 JAR。 我还将这些以及其他所有代码文件都放在了我们的<a href="https://github.com/JBTAdmin/Selenium/tree/master/AdvancedWebDriver/Reading%20data%20from%20excel"> GitHub 存储库</a>中。</p><p>我们之前已经多次看到这种添加 JAR 来构建路径过程的内容,因此我没有在重复它(有关详细说明,请参阅此<a href="https://javabeginnerstutorial.com/selenium/9b-webdriver-eclipse-setup/">文章</a>的步骤 3)。</p><h2><strong>步骤 3:</strong></h2><p>创建一个新类“<strong> ExcelOperationsUsingPOI.java </strong>”。 在此类中,让我们有一种从特定位置读取 excel 文件的特定图纸的方法。</p><li>通过传递您要打开的 excel 文件的完整文件路径来创建 File 类的对象-<code data-enlighter-language="java">File file = new File(filePath+"\\"+fileName); </code></li><li>下一步是创建一个<em> FileInputStream </em>对象,以获取 excel 文件的输入字节-<code data-enlighter-language="java">FileInputStream inputStream = new FileInputStream(file); </code></li><li>创建一个工作簿对象-<code data-enlighter-language="java">Workbook myWorkbook = null; </code></li><li>Excel 文件在大多数情况下可以具有两个扩展名。 “.xls”或“.xlsx”。 通过使用子字符串方法拆分文件名来找到扩展名,并相应地创建 Workbook 对象。</li><pre><code class="language-java">//indexOf gives the index of . in the file name //substring method splits the string starting from index of . to the end String fileExtensionName = fileName.substring(fileName.indexOf(".")); //Check condition if the file is xlsx file if(fileExtensionName.equals(".xlsx")){ //If it is xlsx file then create object of XSSFWorkbook class myWorkbook = new XSSFWorkbook(inputStream); } //Check condition if the file is xls file else if(fileExtensionName.equals(".xls")){ //If it is xls file then create object of HSSFWorkbook class myWorkbook = new HSSFWorkbook(inputStream); }</code></pre><li>使用传递的确切工作表名称,可以读取特定工作表-<code data-enlighter-language="java">Sheet mySheet = myWorkbook.getSheet(sheetName); </code></li><p>现在,使用行和列很容易,它们的交点将为我们提供我们希望读取的单元格内容。</p><p>现在让我们来看一下实现到目前为止讨论的全部功能的代码,</p><h3><strong> ExcelOperationsUsingPOI.java </strong></h3><pre><code class="language-java">import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelOperationsUsingPOI { public static void readExcel(String filePath,String fileName,String sheetName) throws IOException{ //Create a object of File class to open xlsx file File file = new File(filePath+"\\"+fileName); //Create an object of FileInputStream class to read excel file FileInputStream inputStream = new FileInputStream(file); Workbook myWorkbook = null; //Find the file extension by spliting file name in substring and getting only extension name //indexOf gives the index of . in the file name //substring method splits the string starting from index of . to the end String fileExtensionName = fileName.substring(fileName.indexOf(".")); //Check condition if the file is xlsx file if(fileExtensionName.equals(".xlsx")){ //If it is xlsx file then create object of XSSFWorkbook class myWorkbook = new XSSFWorkbook(inputStream); } //Check condition if the file is xls file else if(fileExtensionName.equals(".xls")){ //If it is xls file then create object of HSSFWorkbook class myWorkbook = new HSSFWorkbook(inputStream); } //Read sheet inside the workbook by its name Sheet mySheet = myWorkbook.getSheet(sheetName); //Find number of rows in excel file int rowCount = mySheet.getLastRowNum()- mySheet.getFirstRowNum(); //Create a loop over all the rows of excel file to read it for (int i = 0; i &lt; rowCount+1; i++) { Row row = mySheet.getRow(i); //Create a loop to print cell values in a row for (int j = 0; j &lt; row.getLastCellNum(); j++) { //Print excel data in console System.out.print(row.getCell(j).getStringCellValue()+"|| "); } System.out.println(); } } }</code></pre><h3><strong> ReadExcelData.java </strong></h3><p>用于调用 readExcel 方法并传递必需的参数。</p><pre><code class="language-java">import java.io.IOException; import com.blog.utility.ExcelOperationsUsingPOI; public class ReadExcelData { public static void main(String[] args) { try { ExcelOperationsUsingPOI.readExcel("E:\\Selenium", "ReadUsingPOI.xlsx", "Demographics"); } catch (IOException e) { e.printStackTrace(); } } }</code></pre><p><span class="ezoic-adpicker-ad" id="ezoic-pub-ad-placeholder-124"> </span> <span class="ezoic-ad box-4 adtester-container adtester-container-124" data-ez-name="javabeginnerstutorial_com-box-4" style="display:block !important;float:none;margin-bottom:2px !important;margin-left:0px !important;margin-right:0px !important;margin-top:2px !important;min-height:110px;min-width:728px;text-align:center !important;"> <span class="ezoic-ad ezoic-adl" ezah="90" ezaw="728" id="div-gpt-ad-javabeginnerstutorial_com-box-4-0" style="position:relative;z-index:0;display:inline-block;min-height:90px;min-width:728px;"> </span> </span>注释使代码不言自明。 所考虑的 Excel 工作表中的数据如下所示,</p><p><img alt="Excel Sheet" class="alignnone size-full wp-image-13588" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/07/3_ExcelSheet.jpg" height="287" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20357%20287'%3E%3C/svg%3E" width="357"/></p><noscript><img alt="Excel Sheet" class="alignnone size-full wp-image-13588" height="287" src="img/86b09846221b07ad4f56bd5bde566b64.png" width="357"/><p>使用我们的代码访问此信息将按预期方式打印出所有用管道分隔的值,以便将其控制台。</p><p><img alt="excel console output" class="alignnone size-full wp-image-13587" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/07/2_ConsoleOutput.jpg" height="177" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20450%20177'%3E%3C/svg%3E" width="450"/></p><noscript><img alt="excel console output" class="alignnone size-full wp-image-13587" height="177" src="img/afeb40dbbf98d4b1f60208d231d21f9c.png" width="450"/><p>如果您想检索代码段,请在注释部分大声疾呼,</p><ol><li>给定条目的从零开始的行和列索引</li><li>使用给定的从零开始的行和列索引的值</li><li>基于给定条目的列表中的所有行值</li><li>基于给定条目的列表中的所有列值</li></ol><p>试用这些功能,让我知道您是否遇到颠簸。</p><p>祝你今天愉快!</p><div class="sticky-nav" style="font-size: 15px;"><div class="sticky-nav-image"></div><div class="sticky-nav-holder"><div class="sticky-nav_item"><h6 class="heading-sm">下一篇文章</h6></div><h5 class="sticky-nav_heading " style="font-size: 15px;"><a href="https://javabeginnerstutorial.com/selenium/10k-advanced-webdriver-using-log4j-part-1/" title="10k. Advanced WebDriver – Using Log4j Part 1"> 10k。 高级 WebDriver – 使用 Log4j 第 1 部分</a></h5></div></div> </body> </html></noscript>
\ No newline at end of file
![POI download link](img/66dde6eb58d06604bfe3993478f8010c.png)
## **步骤 2:**
将这些 JAR 添加到我们的项目构建路径中。 确保选择“`poi-x.xx`”,“`ooxml-lib`”和“`lib`”文件夹下的所有 JAR。 我还将这些以及其他所有代码文件都放在了我们的 [GitHub 存储库](https://github.com/JBTAdmin/Selenium/tree/master/AdvancedWebDriver/Reading%20data%20from%20excel)中。
我们之前已经多次看到这种添加 JAR 来构建路径过程的内容,因此我没有在重复它(有关详细说明,请参阅此[文章](https://javabeginnerstutorial.com/selenium/9b-webdriver-eclipse-setup/)的步骤 3)。
## **步骤 3:**
创建一个新类“`ExcelOperationsUsingPOI.java`”。 在此类中,让我们有一种从特定位置读取 excel 文件的特定图纸的方法。
* 通过传递您要打开的 excel 文件的完整文件路径来创建`File`类的对象 - `File file = new File(filePath+"\\"+fileName);`
* 下一步是创建一个`FileInputStream`对象,以获取 excel 文件的输入字节 - `FileInputStream inputStream = new FileInputStream(file);`
* 创建一个工作簿对象 - `Workbook myWorkbook = null;`
* Excel 文件在大多数情况下可以具有两个扩展名。 “`.xls`”或“`.xlsx`”。 通过使用子字符串方法拆分文件名来找到扩展名,并相应地创建`Workbook`对象。
```java
//indexOf gives the index of . in the file name
//substring method splits the string starting from index of . to the end
String fileExtensionName = fileName.substring(fileName.indexOf("."));
//Check condition if the file is xlsx file
if(fileExtensionName.equals(".xlsx")){
//If it is xlsx file then create object of XSSFWorkbook class
myWorkbook = new XSSFWorkbook(inputStream);
}
//Check condition if the file is xls file
else if(fileExtensionName.equals(".xls")){
//If it is xls file then create object of HSSFWorkbook class
myWorkbook = new HSSFWorkbook(inputStream);
}
```
* 使用传递的确切工作表名称,可以读取特定工作表 - `Sheet mySheet = myWorkbook.getSheet(sheetName);`
现在,使用行和列很容易,它们的交点将为我们提供我们希望读取的单元格内容。
现在让我们来看一下实现到目前为止讨论的全部功能的代码,
### **`ExcelOperationsUsingPOI.java`**
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelOperationsUsingPOI {
public static void readExcel(String filePath,String fileName,String sheetName) throws IOException{
//Create a object of File class to open xlsx file
File file = new File(filePath+"\\"+fileName);
//Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
Workbook myWorkbook = null;
//Find the file extension by spliting file name in substring and getting only extension name
//indexOf gives the index of . in the file name
//substring method splits the string starting from index of . to the end
String fileExtensionName = fileName.substring(fileName.indexOf("."));
//Check condition if the file is xlsx file
if(fileExtensionName.equals(".xlsx")){
//If it is xlsx file then create object of XSSFWorkbook class
myWorkbook = new XSSFWorkbook(inputStream);
}
//Check condition if the file is xls file
else if(fileExtensionName.equals(".xls")){
//If it is xls file then create object of HSSFWorkbook class
myWorkbook = new HSSFWorkbook(inputStream);
}
//Read sheet inside the workbook by its name
Sheet mySheet = myWorkbook.getSheet(sheetName);
//Find number of rows in excel file
int rowCount = mySheet.getLastRowNum()- mySheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for (int i = 0; i < rowCount+1; i++) {
Row row = mySheet.getRow(i);
//Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
//Print excel data in console
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
System.out.println();
}
}
}
```
### **`ReadExcelData.java`**
用于调用`readExcel`方法并传递必需的参数。
```java
import java.io.IOException;
import com.blog.utility.ExcelOperationsUsingPOI;
public class ReadExcelData {
public static void main(String[] args) {
try {
ExcelOperationsUsingPOI.readExcel("E:\\Selenium", "ReadUsingPOI.xlsx", "Demographics");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注释使代码不言自明。 所考虑的 Excel 工作表中的数据如下所示,
![Excel Sheet](img/86b09846221b07ad4f56bd5bde566b64.png)
使用我们的代码访问此信息将按预期方式打印出所有用管道分隔的值,以便将其控制台。
![excel console output](img/afeb40dbbf98d4b1f60208d231d21f9c.png)
如果您想检索代码段,请在注释部分大声疾呼,
1. 给定条目的从零开始的行和列索引
2. 使用给定的从零开始的行和列索引的值
3. 基于给定条目的列表中的所有行值
4. 基于给定条目的列表中的所有列值
试用这些功能,让我知道您是否遇到颠簸。
祝你今天愉快!
此差异已折叠。
......@@ -43,7 +43,7 @@
* 元素的顺序将与插入顺序相同。
* 它允许`NULL`值。
*`HashSet`一样,它为基本操作提供恒定的时间性能。
*接列表上的迭代时间与大小成正比。
* 链表上的迭代时间与大小成正比。
* 初始容量和负载因子决定`LinkedHashSet`的性能。
* 它不同步。
* 此类的`Iterator`方法返回的迭代器为快速失败。
......
......@@ -200,4 +200,109 @@ public class eListener {
上面编写的代码显示了 Java 中不使用 Lambda 表达式的事件侦听器的示例。 因此,您必须熟悉该代码。 使用了简单的`JButton``,JFrame``JTextField`。 当用户单击按钮时,文本字段将显示 Hello World 消息。 这是输出
<noscript><img class="wp-image-12604 aligncenter" sizes="(max-width: 443px) 100vw, 443px" src="img/303dddce88f78b1ebf45d69030f6fe44.png" srcset="https://javabeginnerstutorial.com/wp-content/uploads/2018/02/word-image.jpeg 443w, https://javabeginnerstutorial.com/wp-content/uploads/2018/02/word-image-300x131.jpeg 300w"/><p><strong>具有 Lambda 表达式的事件监听器</strong></p><p>现在使用 Lambda Expression 检查事件侦听器。 转到 eclipse 并创建一个名为<strong> eListenerLambda 的新类。 </strong>打开并粘贴以下代码。</p><pre><code class="language-java">import javax.swing.JButton; //import for JButton class import javax.swing.JFrame; //import for JFrame class import javax.swing.JTextField; //import for JTextField public class eListenerLambda { //event listener class without Lambda Expressions static JTextField textfield; static JButton button; static JFrame frame; public static void main(String[] args) { textfield=new JTextField(); button=new JButton("click"); frame=new JFrame("Event Listener without using Lambda Expression"); //set positions of text field and button textfield.setBounds(50, 50,150,20); button.setBounds(80,100,70,30); // lambda expression implementing here. button.addActionListener(e-&gt; {textfield.setText("hello world");}); frame.add(textfield); frame.add(button); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); frame.setSize(300, 200); frame.setVisible(true); } }</code></pre><p>上面编写的代码显示了带有 Lambda Expression 的 Java 事件侦听器的示例。 如果我们将这两个代码进行比较,您将检查第一个示例中的动作侦听器代码是否包含三个语句,而使用 Lambda Expression 可以在一个语句中解决问题。 这两个代码的输出与上面显示的相同。</p><h3>使用 Lambda 表达式的比较器示例</h3><p>让我们再看看使用 Lambda Expression 作为比较器示例的另一段代码。 创建一个新类,并将其命名为<strong> Comparatorlambda </strong> .java。 打开它并粘贴以下代码。</p><pre><code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.List; //account class holds the details of a bank account of customers like account number, name and account balance class Account{ int accountNumber; String name; float AccountBalance; public Account(int accountNumber, String name, float AccountBalance) { super(); this.accountNumber = accountNumber; this.name = name; this.AccountBalance = AccountBalance; } } //comparator class using Lambda Expressions public class Comparatorlambda{ public static void main(String[] args) { List&lt;Account&gt; list=new ArrayList&lt;Account&gt;(); //Adding account details in list list.add(new Account(00235,"Harry",25000)); list.add(new Account(11687,"Donald",30088)); list.add(new Account(27865,"Caristano",15078)); System.out.println("Sorting on the basis of account name..."); // implementing lambda expression Collections.sort(list,(p1,p2)-&gt;{ return p1.name.compareTo(p2.name); }); System.out.println("Account Number: Account Name: Account Balance:"); for(Account p:list){ System.out.println(p.accountNumber+" \t\t"+p.name+" \t\t"+p.AccountBalance); } } }</code></pre><p>此示例具有一个帐户类,其中包含名称,号码和帐户余额之类的帐户信息。 Lambda 表达式用于根据帐户名称对帐户进行比较和排序。 这是用于此目的的 Lambda 表达式。</p><pre><code class="language-java">Collections.sort(list,(p1,p2)-&gt;{return p1.name.compareTo(p2.name); });</code></pre><p>以下是此代码的输出</p><p><img class="wp-image-12605 aligncenter" data-lazy-src="https://javabeginnerstutorial.com/wp-content/uploads/2018/02/word-image-1-1.jpeg" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E"/></p><noscript><img class="wp-image-12605 aligncenter" src="img/b940eb92cb3455c80aefcc6635a9e212.png"/><h2><strong>结论</strong></h2><p>Lambda 表达式用于定义函数式接口的内联实现。 您在上面的示例中看到,Lambda Expressions 节省了我们的时间,并大大减少了代码语句。 它通过促进函数式编程为 Java 提供了强大的功能。 Java 的这一新功能改变了完整的编码方式,简化了开发过程,因为它利用了多核环境的并行功能。</p> </body> </html></noscript>
\ No newline at end of file
![](img/303dddce88f78b1ebf45d69030f6fe44.png)
**具有 Lambda 表达式的事件监听器**
现在使用 Lambda 表达式检查事件侦听器。 转到 eclipse 并创建一个名为`eListenerLambda`的新类。打开并粘贴以下代码。
```java
import javax.swing.JButton; //import for JButton class
import javax.swing.JFrame; //import for JFrame class
import javax.swing.JTextField; //import for JTextField
public class eListenerLambda {
//event listener class without Lambda Expressions
static JTextField textfield;
static JButton button;
static JFrame frame;
public static void main(String[] args) {
textfield=new JTextField();
button=new JButton("click");
frame=new JFrame("Event Listener without using Lambda Expression");
//set positions of text field and button
textfield.setBounds(50, 50,150,20);
button.setBounds(80,100,70,30);
// lambda expression implementing here.
button.addActionListener(e-> {textfield.setText("hello world");});
frame.add(textfield);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
```
上面编写的代码显示了带有 Lambda 表达式的 Java 事件侦听器的示例。 如果我们将这两个代码进行比较,您将检查第一个示例中的动作侦听器代码是否包含三个语句,而使用 Lambda 表达式可以在一个语句中解决问题。 这两个代码的输出与上面显示的相同。
### 使用 Lambda 表达式的比较器示例
让我们再看看使用 Lambda 表达式作为比较器示例的另一段代码。 创建一个新类,并将其命名为`Comparatorlambda.java`。 打开它并粘贴以下代码。
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//account class holds the details of a bank account of customers like account number, name and account balance
class Account{
int accountNumber;
String name;
float AccountBalance;
public Account(int accountNumber, String name, float AccountBalance) {
super();
this.accountNumber = accountNumber;
this.name = name;
this.AccountBalance = AccountBalance;
}
}
//comparator class using Lambda Expressions
public class Comparatorlambda{
public static void main(String[] args) {
List<Account> list=new ArrayList<Account>();
//Adding account details in list
list.add(new Account(00235,"Harry",25000));
list.add(new Account(11687,"Donald",30088));
list.add(new Account(27865,"Caristano",15078));
System.out.println("Sorting on the basis of account name...");
// implementing lambda expression
Collections.sort(list,(p1,p2)->{
return p1.name.compareTo(p2.name);
});
System.out.println("Account Number: Account Name: Account Balance:");
for(Account p:list){
System.out.println(p.accountNumber+" \t\t"+p.name+" \t\t"+p.AccountBalance);
}
}
}
```
此示例具有一个帐户类,其中包含名称,号码和帐户余额之类的帐户信息。 Lambda 表达式用于根据帐户名称对帐户进行比较和排序。 这是用于此目的的 Lambda 表达式。
```java
Collections.sort(list,(p1,p2)->{return p1.name.compareTo(p2.name); });
```
以下是此代码的输出
![](img/b940eb92cb3455c80aefcc6635a9e212.png)
## **结论**
Lambda 表达式用于定义函数式接口的内联实现。 您在上面的示例中看到,Lambda 表达式节省了我们的时间,并大大减少了代码语句。 它通过促进函数式编程为 Java 提供了强大的功能。 Java 的这一新功能改变了完整的编码方式,简化了开发过程,因为它利用了多核环境的并行功能。
\ No newline at end of file
......@@ -9,4 +9,24 @@
* 只要任何非守护程序线程仍在运行,Java 应用就会继续执行(虚拟机实例继续运行)。 Java 应用的所有非守护程序线程都终止时,虚拟机实例将退出。 如果得到安全管理者的允许,则应用还可以通过调用`Runtime``System`类的`exit()`方法来使其自身灭亡。
<noscript><img alt="" height="299" src="img/84ced9a2cb730f97cce54806e6a7946b.png" width="670"/><p align="center"><strong> </strong></p><p align="center"><strong> Java 虚拟机的体系结构</strong></p><li>所有的 JVM 都包含两个组成部分</li><p style="padding-left: 60px;"><em> <span style="text-decoration: underline;">类加载器子系统</span> </em> <span style="text-decoration: underline;"></span>一种机制,用于加载具有完全限定名称的类型(类和接口)。</p><p style="padding-left: 60px;"><em> <span style="text-decoration: underline;">执行引擎</span> </em>:一种机制,负责执行已加载类的方法中包含的指令。</p><li style="text-align: justify;">当 Java 虚拟机运行程序时,它需要内存来存储许多东西,包括字节码,已加载的类文件中的信息,程序实例化的对象,方法的参数,返回值,局部变量以及中间的计算结果。</li><li style="text-align: justify;">虚拟机的不同实现可能具有非常不同的内存限制。 一些实现可能需要大量内存才能工作,而其他实现可能很少。 一些实现可能能够利用虚拟内存,而其他一些则不能。 运行时数据区规范的抽象性质有助于简化在各种计算机和设备上实现 Java 虚拟机的过程。</li><li style="text-align: justify;">不同的 Java 程序具有不同的 jvm 实例。 如果我执行一个类,则一个单独的 jvm 实例将处理该类</li><li style="text-align: justify;">当虚拟机加载类文件时,它会从类文件中包含的二进制数据中解析有关类型的信息。 它将类型信息放入方法区域,将程序实例化的所有对象放入堆。</li><li style="text-align: justify;">随着每个新线程的出现,它获得了自己的<em> pc 寄存器</em>(程序计数器)和<em> Java 栈</em>。 如果线程正在执行 Java 方法(不是本机方法),则 pc 寄存器的值指示要执行的下一条指令。 线程的 Java 栈存储该线程的 Java(非本机)方法调用状态。</li><li style="text-align: justify;">Java 栈由<em>栈帧</em>(或<em></em>)组成。 栈框架包含一个 Java 方法调用的状态。 当线程调用方法时,Java 虚拟机将新框架推送到该线程的 Java 栈上。 该方法完成后,虚拟机将弹出并丢弃该方法的帧</li><li style="text-align: justify;">Java 虚拟机包含两种类加载器:java.lang.ClassLoader</li><h3>b <em> ootstrap 类加载器,用户定义的类加载器</em></h3><li style="text-align: justify;">正在运行的程序的每个线程都有其自己的<strong>程序计数器</strong>寄存器或程序计数器,它们是在线程启动时创建的。 pc 寄存器的大小为一个字,因此它既可以保存本机指针,也可以保存 returnAddress。 当线程执行 Java 方法时,pc 寄存器包含该线程正在执行的当前指令的地址。 “地址”可以是本机指针,也可以是方法字节码开头的偏移量。 如果线程正在执行本机方法,则 pc 寄存器的值未定义。</li><li>这里有两叠</li><p><em> <strong> Java 栈:</strong> </em>由 JVM 维护,</p><p><em> <strong>本机栈:</strong> </em>取决于。</p><p>大家好,请评论我的帖子。 如果我的帖子有任何问题,请随时进行纠正,谢谢。</p><p> </p> </body> </html></noscript>
\ No newline at end of file
![](img/84ced9a2cb730f97cce54806e6a7946b.png)
**Java 虚拟机的体系结构**
* 所有的 JVM 都包含两个组成部分
*类加载器子系统*:一种机制,用于加载具有完全限定名称的类型(类和接口)。
*执行引擎*:一种机制,负责执行已加载类的方法中包含的指令。
* 当 Java 虚拟机运行程序时,它需要内存来存储许多东西,包括字节码,已加载的类文件中的信息,程序实例化的对象,方法的参数,返回值,局部变量以及中间的计算结果。
* 虚拟机的不同实现可能具有非常不同的内存限制。 一些实现可能需要大量内存才能工作,而其他实现可能很少。 一些实现可能能够利用虚拟内存,而其他一些则不能。 运行时数据区规范的抽象性质有助于简化在各种计算机和设备上实现 Java 虚拟机的过程。
* 不同的 Java 程序具有不同的 jvm 实例。 如果我执行一个类,则一个单独的 jvm 实例将处理该类
* 当虚拟机加载类文件时,它会从类文件中包含的二进制数据中解析有关类型的信息。 它将类型信息放入方法区域,将程序实例化的所有对象放入堆。
* 随着每个新线程的出现,它获得了自己的 *pc 寄存器*(程序计数器)和 *Java 栈*。 如果线程正在执行 Java 方法(不是本机方法),则 pc 寄存器的值指示要执行的下一条指令。 线程的 Java 栈存储该线程的 Java(非本机)方法调用状态。
* Java 栈由*栈帧*(或*帧*)组成。 栈框架包含一个 Java 方法调用的状态。 当线程调用方法时,Java 虚拟机将新框架推送到该线程的 Java 栈上。 该方法完成后,虚拟机将弹出并丢弃该方法的帧
* Java 虚拟机包含两种类加载器:`java.lang.ClassLoader` bootstrap 类加载器,用户定义的类加载器。
* 正在运行的程序的每个线程都有其自己的**程序计数器**寄存器或程序计数器,它们是在线程启动时创建的。 pc 寄存器的大小为一个字,因此它既可以保存本机指针,也可以保存 returnAddress。 当线程执行 Java 方法时,pc 寄存器包含该线程正在执行的当前指令的地址。 “地址”可以是本机指针,也可以是方法字节码开头的偏移量。 如果线程正在执行本机方法,则 pc 寄存器的值未定义。
* 这里有两个栈,Java 栈:由 JVM 维护,本机栈:取决于。
大家好,请评论我的帖子。 如果我的帖子有任何问题,请随时进行纠正,谢谢。
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册