Java BASICS (new features and reflection of myeclipse, debug, junit, and JDK5)
Mind Map
1. install and use myeclipse
* Eclipse: a free development tool
* Myeclipse: it is a paid plug-in, cracking myeclipse,
** Installation directory requirements: Chinese characters and spaces are not allowed
** After the installation is complete, select a workspace which cannot contain Chinese characters or spaces.
* Cracking myeclipse
** Before running the run. bat file, you must install jdk and configure the environment variables.
* Use of myeclipse
* Create a project
-Javaproject web project
-Select the dependent jdk. You can use the jdk that comes with myeclipse or the installed jdk.
* Create a package
-Cn. itcast. test XX. XX. XX
* Create a class in the package
-Class naming rules:
** Uppercase letters are required.
For example: TestDemo1 UserManager
* Create a method in the class
Publicvoid test1 (parameter list ){
Method body or return value;
}
-Method naming rules
Lowercase letters such as addNum ()
* Define variables
-Variable naming rules
** Lowercase letters: the first letter of the second word, for example, userName.
* There is also one way to name these items.
** Use Chinese pinyin to name yonghuming mima
** You cannot mix Chinese pinyin with English letters.
UserMing
* The most basic naming principle: You can see what the name means.
* The code must be indented.
* Run the program run asjava application
Debug asjava application
2. debug mode (breakpoint debugging mode)
* Use this mode to debug the program (see the data changes in the Program)
* When Using debug, you need to set a breakpoint (to stop the program running on this line)
-Display the row number
-Double-click a dot on the left to indicate that a breakpoint is set.
* Run the program in debug as mode.
-Prompt whether to go to the debugging page, yes
-There is a green entry at the breakpoint, indicating that the program stops on this line and does not run down.
* The program can be executed downward,
-The step over shortcut is F6 (one-step execution)
-Resume F8: indicates that debugging is complete and runs directly down.
** For example, if there is a breakpoint after the current breakpoint, it will jump to the next breakpoint,
** If there is no breakpoint after the current breakpoint, the program runs directly.
* Another purpose of debug
** View the source code of a program
** F5 step into: Enter the Method
** F7 step return: return
3. Use of myeclipse shortcut keys
* The Code prompts alt/
* Fast export package ctrlshift o
* Single line comment ctrl/
* Remove the single line comment ctrl/
* Multi-line comment ctrl shift/
* Remove the multi-line comment ctrlshift \
* Delete row ctrl d
4. Use of junit
* Unit test
* The test object is a method in a class.
* Juint is not part of javase and you want to use the imported jar package.
** However, the jar package of junit is included in myeclipse.
* First, junit version 3.x 4.x
* When testing a method, the method naming Rule public void method name (){}
* Run the test method in Annotation mode.
** @ Test: unit Test of the method.
--- @ Test
Publicvoid testAdd1 (){
TestJunittest01 = new TestJunit ();
Test01.testAdd (2, 3 );
}
-Select the method name and right-click run as --- junit test.
-If a green bar appears, the method test is successful.
-If a red-brown stripe appears, the method test fails.
--- To run multiple test methods in the class, click another location in the class and run as --- junit test
** @ Ignore: indicates that no unit test is performed for this method.
** @ Before: run in each method
** @ After: Run After each method
** Assertions (understanding)
-Assert. assertEquals ("test expected value", "actual value of method running ")
New Features of jdk5.0
Jdk 1.11.2 1.4 5.0
** Generic, enumeration, static import, Automatic Disassembly and removal box, enhanced for, and variable parameters
** Reflection
5. Introduction to generics
* Why use generics?
-Generally used on a set
** For example, if a value of the string type is put into the set, the value is put into the set, and the type of the string type is lost. It can only be of the object type,
At this time, for example, if you want to convert the type of the value, it is easy to see a type conversion error. To solve this problem, you can use the generic type to solve it.
* How to Use generics on a set
-List setmap
-Generic syntax set For example, List
* Writing in a wildcard is an object, and the String cannot write basic data types, such as int (****)
** Write basic data types to corresponding packaging classes
Byte -- Byte
Short -- Short
Int -- Integer
Long -- Long
Float -- Float
Double -- Double
Char -- Character
Boolean -- Boolean
* Use generics on the list
Three ArrayList Functions list Vector
Code:
@ Test
Publicvoid testList (){
List List = new ArrayList ();
List. add ("aaa ");
List. add ("bbb ");
List. add ("ccc ");
// There are three methods to traverse the list set
// Normal for loop iterator enhanced
// Common for Loop
For (inti = 0; I
Strings = list. get (I );
System. out. println (s );
}
System. out. println ("=================== ");
// Use enhancement
For (String s1: list ){
System. out. println (s1 );
}
System. out. println ("=================== ");
// Use the iterator to traverse
Iterator It = list. iterator ();
While (it. hasNext ()){
System. out. println (it. next ());
}
* Job 1: three differences between ArrayList listing Vector
* Use generics on set
Code:
// Use the set for generics
@ Test
Publicvoid testSet (){
Set Set = new HashSet ();
Set. add ("www ");
Set. add ("qqq ");
Set. add ("zzz ");
// Set. add ("qqq ");
// You can use either of the following methods to traverse a set:
// Iterator enhancement
// Use enhanced for Traversal
For (String s2: set ){
System. out. println (s2 );
}
System. out. println ("=================== ");
// Use the iterator to traverse
Iterator It1 = set. iterator ();
While (it1.hasNext ()){
System. out. println (it1.next ());
}
}
* Use generics on map
-Map structure: key-valu format
Code:
// Use generics on map
@ Test
Publicvoid testMap (){
Map Map = new HashMap ();
Map. put ("aaa", "111 ");
Map. put ("bbb", "222 ");
Map. put ("ccc", "333 ");
// There are two ways to traverse a map:
// 1. obtain all the keys. Use the get method to obtain the value through the key.
// 2. Obtain the relationship between key and value
// Use the first method to traverse
// Obtain all keys
Set Sets = map. keySet ();
// Traverses the set returned by all keys
For (String key: sets ){
// Obtain value through key
Stringvalue = map. get (key );
System. out. println (key + ":" + value );
}
System. out. println ("================ ");
// Obtain the relationship between key and value.
Set > Sets1 = map. entrySet ();
// Traverse sets1
For (Entry Entry: sets1 ){
// The entry is the relationship between key and value.
Stringkeyv = entry. getKey ();
Stringvaluev = entry. getValue ();
System. out. println (keyv + ":" + valuev );
}
}
6. Generic usage in methods
* Defines an array to exchange array elements at a specified position.
* The method logic is the same, but the data types are different. In this case, the generic method is used.
*/*
* To use the generic method, you need to define a type that uses uppercase letters to represent T: This T represents any type.
* Before the return value void
* ======== Indicates that a type is defined. This type is T.
* This type can be used below T
**/
Publicstatic Void swap1 (T [] arr, int a, int B ){
Ttemp = arr [a];
Arr [a] = arr [B];
Arr [B] = temp;
}
** Job 2: implement a generic method that accepts any array and reverses all elements in the array.
7. Usage of generics in classes (understanding)
* Define a type on a class, which can be directly used in the class
* Public class TestDemo04 {
// The T type can be directly used in the class
Taa;
Publicvoid test11 (T bb ){}
// Write a static method to the generic type defined above the class. It cannot be used in a static method.
Publicstatic void test12 (A cc ){}
}
8. Enumeration Overview
* What is enumeration?
** The value must be within a certain range. This value can only be any of the values in this range.
** Real-world scenario: Traffic Signal lights in three colors, but only one of the three colors can be highlighted at a time.
* Use the enum keyword.
** Enum Color3 {
RED, GREEN, YELLOW;
}
* Enumeration construction methods are private.
* Special Enumeration operations (learn more)
** There is a constructor in the enumeration class.
** There are parameters in the constructor. You need to write parameters on each instance.
** There are abstract methods in the enumeration class.
** Rewrite this abstract method in each instance of enumeration.
9. Enumeration api operations
** Name (): returns the enumerated name.
** Ordinal (): subscript of the enumeration. The subscript starts from 0.
** ValueOf (Class EnumType, String name): obtains the enumerated object.
** There are two other methods, both of which are not in the api. Two methods are generated during compilation.
* ** Valueof (String name) Conversion enumeration object
* ** Values () obtains an array of all enumerated objects.
* Exercise: conversion between enumeration objects, enumeration object subscript, and enumeration Object Name Representation
-// Knows the enumerated object and obtains the enumerated name and subscript.
@ Test
Publicvoid test1 (){
// Obtain the enumerated object
Color100c100 = Color100.RED;
// Enumeration name
Stringname = c100.name ();
// Subscript of enumeration
Intidx = c100.ordinal ();
System. out. println (name + "" + idx );
}
-// Know the enumeration name to obtain the enumerated object and subscript
@ Test
Publicvoid test2 (){
Stringname1 = "GREEN ";
// Obtain the object
Color100c1 = Color100.valueOf (name1 );
// Enumerative subscript
Intidx1 = c1.ordinal ();
System. out. println (idx1 );
}
-// Know the subscript of the enumeration to obtain the enumerated object and name
@ Test
Publicvoid test3 (){
Intidx2 = 2;
// Obtain the enumerated object
Color100 [] cs = Color100.values ();
// Obtain the object based on the subscript
Color100c12 = cs [idx2];
// Obtain the enumerated name.
Stringname = c12.name ();
System. out. println (name );
}
10. Static import (learn more)
* You can directly use the static import method in the code to import static methods or constants.
* Import static XX. XX. xxx
* Import static java. lang. System. out;
Importstatic java. util. Arrays. sort;
** For example, a calculator is implemented in the Math class.
11. Automatic Disassembly box
* Packing
** Convert basic data types into packaging classes
* Binning
** Convert a packaging class to a basic data type
** // Automatic Packing
Integeri = 10;
// Automatically unpack
Intm = I;
** In jdk1.4, how does one implement packing and unpacking?
-// Implement disassembly box in jdk1.4
Publicvoid test1 (){
// Packing
Integerm = new Integer (10 );
// Unpack
Inta = m. intValue ();
}
** Jdk is backward compatible.
-For example, the code written in jdk1.4 can also be run in 5.0.
** Exercise: backward compatible
= The result of execution is to call doSomething (double m)
= This method must be called in jdk1.4 first. If the following method is called, type conversion is required, but jdk1.4 cannot implement Automatic Disassembly box
= Because jdk is backward compatible, calling this method in jdk1.4 will still call this method in jdk5.0
Publicstatic void main (String [] args ){
DoSomething (10 );
}
Publicstatic void doSomething (double m ){
System. out. println ("double ......");
}
Publicstatic void doSomething (Integer ){
System. out. println ("integer .....");
}
** Remember: The packaging class corresponding to the eight basic data types
* Int --- Integer
* Char --- Character
12. Enhance the for Loop (*****)
* Syntax for (the retrieved value: the set to be traversed ){}
-For (String s: list ){
System. out. println (s );
}
* Application Scenario: array; the set that implements the Iterable interface can use an enhanced for loop.
* Use enhanced for loop traversal on the set
List set implements the Iterator interface, so you can use the enhanced for Loop
The enhancement for loop cannot be used for map, and the Iterator interface is not implemented. Therefore, the enhancement for loop cannot be used.
* Enhancement of the for Loop: to replace the iterator
** The underlying layer of enhancement for is implemented by the iterator.
13. Content supplement
(1) Generic Erasure
* First, generics only appear in the source code phase. After compilation, Generics do not exist.
(2) exercise: implement a generic method that accepts arrays of any type and reverses all elements in the array.
Code
Publicstatic Void reverses (T [] arr1 ){
/*
* Basic Idea: swap positions between the first element and the last element, and the second and last elements ....
* Switching length/2
**/
// Traverse the Array
For (inti = 0; I
/* Inttemp = arr1 [0];
Arr1 [0] = arr1 [arr1.length-1]; */
Ttemp = arr1 [I];
Arr1 [I] = arr1 [arr1.length-i-1];
Arr1 [arr1.length-i-1] = temp;
}
}
14. variable parameters
* Scenarios where variable parameters can be used:
** Implement the addition of two numbers and the addition of three numbers.
-- If multiple methods are implemented, the logic in these methods is basically the same. The only difference is the number of passed parameters. variable parameters can be used.
* Variable Parameter definition method data type... array name
* It is understood as an array, which stores the passed parameters.
-Code
Publicstatic void add1 (int... nums ){
// Nums is interpreted as an array, which stores the passed parameters.
// System. out. println (nums. length );
Intsum = 0;
// Traverse the Array
For (inti = 0; I
Sum + = nums [I];
}
System. out. println (sum );
}
* Notes
(1) variable parameters must be written in the parameter list of the method and cannot be defined separately.
(2) Only one variable parameter can be included in the parameter list of the method.
(3) variable parameters in the parameter list of the method must be placed at the end of the Parameter
-Add1 (int a, int... nums)
15. How reflection works ********)
* Application in some code with high versatility
* Most of the frameworks learned later are implemented using reflection.
* Framework development is based on configuration files.
** You have configured a class in the configuration file. You can get all the content in the class through reflection and execute a method in the class.
* All content in the class: properties, constructor without parameters, constructor with parameters, and common methods
* Principle of reflection in drawing Analysis
* First, you need to save the java file to the local hard disk. java
* Compile a java file into a. class file.
* Use jvm to load class files to the memory through classes
* Everything is an object. class files are represented by Class classes in the memory.
* When Using Reflection, you first need to obtain the Class class. After obtaining this Class, you can get all the content in the class file.
-Common methods that contain attribute constructor Methods
* The attribute uses a Filed class
* Constructor
* A common Method uses a class Method
16. Use the non-parameter constructor in the reflection operation class (** write **)
* First obtain the Class
-// Obtain the Class
Classclazz1 = Person. class;
Classclazz2 = new Person (). getClass ();
Classclazz3 = Class. forName ("cn. itcast. test09.Person ");
* For example, if you want to instantiate a class, you can use new instead of new. How can this problem be obtained?
-// Obtain the Class
Classc3 = Class. forName ("cn. itcast. test09.Person ");
// Obtain the Person class instance
Personp = (Person) c3.newInstance ();
* Code
// Construct an operation without Parameters
@ Test
Publicvoid test1 () throws Exception {
// Obtain the Class
Classc3 = Class. forName ("cn. itcast. test09.Person ");
// Obtain the Person class instance
Personp = (Person) c3.newInstance ();
// Set the value
P. setName ("zhangsan ");
System. out. println (p. getName ());
}
17. Use the construction method with parameters in the reflection operation (** write **)
// Construct an operation with Parameters
@ Test
Publicvoid test2 () throws Exception {
// Obtain the Class
Classc1 = Class. forName ("cn. itcast. test09.Person ");
// Use a construction method with Parameters
// C1.getConstructors (); // obtain all Constructors
// The parameter type is passed in the constructor with parameters. The type is passed in the class format.
Constructorcs = c1.getConstructor (String. class, String. class );
// Set the value through the constructor with Parameters
// Create a Person instance using a constructor with Parameters
Personp1 = (Person) cs. newInstance ("lisi", "100 ");
System. out. println (p1.getId () + "" + p1.getName ());
}
18. Use the reflection operation attribute (** write **)
* // Operation name attribute
@ Test
Publicvoid test3 (){
Try {
// Obtain the Class
Classc2 = Class. forName ("cn. itcast. test09.Person ");
// Obtain the name attribute
// C2.getDeclaredFields (); // indicates that all attributes are obtained.
// Obtain the Person class instance
Personp11 = (Person) c2.newInstance ();
// Obtain the attribute using this method. The parameter is the attribute name.
Fieldf1 = c2.getDeclaredField ("name ");
// The operation is performed on private attributes, so the operation is not allowed. You need to set the setAccessible (true) attribute that can be operated on, and you can operate on private attributes.
F1.setAccessible (true );
// Set THE name value set method. There are two parameters: the first parameter class instance and the second parameter is the set value.
F1.set (p11, "wangwu"); // equivalent ";
System. out. println (f1.get (p11); // equivalent to p. name
} Catch (effectione ){
E. printStackTrace ();
}
}
19. use generic operations for common methods (** write **)
* Use the Method class to represent normal methods
* Code
// Operate common methods, such as setName
@ Test
Publicvoid test4 () throws Exception {
// Obtain the Class
Classc4 = Class. forName ("cn. itcast. test09.Person ");
// Obtain the Person instance
Personp4 = (Person) c4.newInstance ();
// Obtain the common method
// C4.getDeclaredMethods (); // obtain all common methods
// Pass two parameters: the first parameter, the method name, and the second parameter, the type of the parameters in the Method
Methodm1 = c4.getDeclaredMethod ("setName", String. class );
// Run the setName method and set the value.
// Use invoke (p4, "niuqi"); pass two parameters: the first parameter, person instance; the second parameter, Set Value
// After the invoke method is executed, it is equivalent to executing the setName method and setting the value niuqi
M1.invoke (p4, "niuqi ");
System. out. println (p4.getName ());
}
* // The Private method of the operation. The value must be set to true.
* // M1.setAccessible (true );
* When the operation method is a static method, because the static method is called by class name. method name, the instance of the class is not required.
* When Using Reflection to perform static operations, instances are not required.
* Write a null value in the first parameter of the invokie method.
-M1.invoke (null, "niuqi ");