Java Foundation (4)

Reflection
    has a class "Java.lang.Class" in Java, which can instantiate an object of type Class for each class, that is to
        say, each class has a corresponding instantiated object of Class            
    as a class ( A) There are three ways to instantiate a Class object:
        · Use a getClass() method inherited from the Object class,
            public final Class getClass() method    
        · Use the "class.Class" method to instantiate a Class object, that is, A.Class
        · Use a static method in the Class class
            public static Class forName (String className)
                The method must know the full name of the class (package name. Class name)
    Simple application of reflection
        We can use reflection to instantiate an instantiated object of a class, to achieve this For one operation, you need to use a method in Class:
            public T newInstance()
                T t =null;
                Class<?> cls=Class.forName(ClassName);
                 t=(T)cls.newInstance();
    reflection calls the constructor
            Get the constructor with parameters
                - get the specified constructor: public Constuctor getConstructor(Class...parameterTypes)
                - get all the constructors: public Constuctor[] getConstructors()    
    reflectively call ordinary methods
            Get the specified method: public Method getMethod(String name,Class...
                parameterTypes)    
            Get all the methods: public Methods [] getMethods()    
            Method call: use the invoke() method to
    reflect the operation
        of the attribute To operate on the attribute, you need to obtain the attribute first, and then Set properties
            Get the specified properties: public Filed getDeclaredFiled(String name)
            Unencapsulate: Filed.setAccessible(true);     
    Reflection can assemble the properties and property values ​​of simple Java class objects into Json strings
        such as: "Person":{ name="Zhang San", "address": Dongguan, "age": 100} This is the Json format        
            Class<?> cls=Class.forName("NewInstance.Person");
                        Person per=(Person) cls.newInstance();
                            per.setAddress("东莞");
                            per.setName("张三");
                            per.setAge(100);
                        StringBuffer sb=new StringBuffer("\"Person\":{");
                            Field [ ]fs=cls.getDeclaredFields();
                                for (int i = 0; i < fs.length; i++) {
                                    fs[i].setAccessible(true);
                                    sb.append("\""+fs[i].getName()+"\"");
                                    sb.append(":"+fs[i].get(per)+",");
                                }
                                    sb.append("}");    
                                System.out.println(sb); To learn io knowledge for file
operations
    , you must first learn the Filed class, which is a class that operates on files, but does not operate on the contents of
    files File
        Constructor: public File (String pathName) pathName is the file directory + file name
        Create a file: public boolean createNewFile() throws IOException
        Create a file directory (folder)
            - create a first-level directory: public boolean mkdir() successfully created Return true
            - create a multi-level directory: public boolean mkdirs() successfully returns true to
    determine whether the directory exists
        First take out the parent path: public File getParentFile()
        Determine whether the directory of the file exists; public boolean exists()
    File deletion: public boolean delete()    
    *Due to the different file separators of different operating systems, for example, "\" for windows system, "/" for Linux
    So we need to dynamically take out the supported separators
        public static final String separator//File.separator
    to get the information
        of the file Get the size of the file: public long length() Get the size of the file, return it in bytes    
        Get the current The first-level directory under the file, returned as an array of String type: public String[]list()
        Get the first-level directory under the current file, and return it as a File array type: public File[]listFiles()
        Get under the drive letter List of all files: public static void printDirs(int level, File file)
        Judging whether it is a directory: public boolean isDirectory()
The operation of file content
    reads or writes data in accordance with the stream
        -byte Stream (operate in units of bytes [byte])
        - character stream (operate in units of characters [char])
            to output data: public abstract class OutputStream{}
                Output content (write content to the specified file) ): public void write(byte[] b)
                    [first convert the data into bytes and store them in a byte array]
                · To output a single byte: public abstract void write (int b)
                    [output one byte at a time, use a while loop to output all the data content]
                · Output a partial byte array: public void write(byte[] b, int off,int len)
                    [off indicates the number of subscripts to output from the array, and len indicates how many bytes to output]
        To use byte streams, follow the steps below:
            Define a file path
            Instantiate The subclass object FileOutputStream of OutputStream
            Perform output operations
            . Because the stream is a resource, it must be closed    
        *Instantiating the subclass object of OutputStream will overwrite the original content. If you want to implement appending, use another
            constructor                        
            OutputStream out=new FileOutputStream(file,true);
            Implement data input: public abstract class InputStream{}
                · Each time a byte is read, the return value is int type: public abstract int read()
                    [Use this method to use the while loop to read]
                ·Read data with an array length each time: public int read(byte[] b)
                    [Return value, if there is data, return the length of the read data, otherwise return -1]
                · Read data of specified length each time: public int read (byte[] b, int off, int len ​​)
                    [return value, if there is still data, return the length of the read data, otherwise return -1]    
        *Generally byte streams are used to read: video, music, pictures, etc., while character streams operate on Chinese.
    Character output stream
        Character stream also needs to instantiate two subclasses FileWrite and FileReader for two abstract classes Writer and Reader
            . Output the content of the character array: public void write (char[] c)
            Output a single character: public void write(int c)
            · Output a string: public void write (String str)
            · Read one character at a time: public int read()
            · Read data of an array length each time: public int read (char[] c )
            ·The length of each read part of the array: public int read(char[] c,int off,int len)    
                [The first parameter is a character array, which is used to save the read content, and the second parameter is the specification Starting from the off-th subscript of the array, the third parameter is the length of the array]    
        The byte stream operation data is in bytes, and the character stream is a character unit
        . The byte stream operates directly on the terminal, while the character stream operates directly on the terminal. The stream needs to be processed by the buffer before it can be operated    
        . When operating the byte stream for the second reason, it will not be affected if it is not closed, and the character stream will not be output and use flash
        . In development, the length of the array is generally defined as 1024 or 2048.    
The operation method of the Collection interface
        Collection is the largest parent interface of a single-valued collection, that is: only one element (single-valued) can be saved at a time
            public boolean add(E e): Add an element to the collection
            public boolean addAll(Collection<? extend E> c): append a collection to the collection
            public void clear(): clear the collection
            public boolean contains(Object o): determine whether the collection is empty, empty does not mean null
            public Iterator Iterator(): instantiate the child for the Iterator interface class object, used to iterate over the collection
            public boolean remove(Object o): To delete an element, it needs the support of equals()
            public int size(): Get the size of the collection
        Collection is the largest parent interface, there are two commonly used sub-interfaces List and Set below,
            and List The interface has two commonly used subclasses arrayList and Vector that implement its interface, and the Set interface has two commonly used subclasses HashSet and TreeSet that implement it.
            Generally do not use the Collection interface, but use its sub-interfaces.
        List interface:
            some important methods have been expanded in this interface.
                public E get (int index) [get the specified element according to the subscript]
                public E set (int index, E element) [set the value of the element with the specified subscript, that is Replacement value]
        ArrayList and Vector
            ArrayList is a new subclass, which was added in JDK1.2 version (1998), Vector is an old subclass, ArrayList
                does not consider thread safety, and its performance is relatively high. Vector considers thread safety, and its performance is relatively high. Low        
        HashSet save data is disordered (determined by subclasses), duplicate data cannot be saved (parent interface cannot be saved)
            If there is duplication of information, it means that there are no hashCode() and equals() methods, and these two methods are used for any object comparison
            . There is also a compareTo() automatic sorting method in the String class.
            The data stored in HashSet is unordered, and the elements cannot be repeated.
            The data stored in TreeSet is ordered and should provide hashCode, equals, compareTo methods

The output of the
    collection There are four kinds of output of the collection:
        Use the Iterator interface to achieve output
            - iter.hasNext() 
        Use the ListIterator interface to achieve output, this method is only suitable for List interface     
            - liter.hasNext() to achieve forward output
            - liter.hasPrevious () To achieve reverse output (to achieve reverse output, you must first achieve forward output)
        Use enhanced for loop output    
            -for(T t:set){}
        Use Enumeration interface output, this way is just Vector    
            -enu.hasMoreEkements ()
        The output of the collection is preferably the iterator method (90%) When the
Map collection        
    saves a pair (key=value) as a unit, we can use the Map interface to complete it    
        . public V put(K key, V value): to the collection Add a certain element
        public V get (Object key): get the corresponding value according to the specified key
        public Set<K> KeySet(): get all the keys in the set, save them in the Set collection and return
        ·public Set<Map.Entry<K,V>> entrySet(): The nested mapping returns the set containing the mapping relationship in the mapping.
        The data stored in the HashMap has no order. If the key value is repeated, the new value will overwrite the old value
        HashMap Is a new subclass, launched in JDK1.2 version, Hashtable is an old subclass
        HashMap does not consider thread safety, high performance, Hashtable considers thread safety, the performance is lower than
        the key or value saved by HashMap can be null, The key or the value stored in Hashtable cannot be empty
        . Use your own custom type as the key, then you need to provide hashCode() and equals() for the corresponding class.
            In development, the String type is generally used as the key value.
        To output the Map collection, use When entrySet is converted into Set, when the set is saved, it will automatically
        encapsulate the pair of key and value as an object of type Map.Entry. When calling, it uses "external interface. internal interface"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325193667&siteId=291194637