2018.8.1 reflection and synchronization in Java

Source: Internet
Author: User
Tags reflection

Why use Sync?
    java允许多线程并发控制,当多个线程同时操作一个可共享的资源变量时(如数据的增删改查),     将会导致数据不准确,相互之间产生冲突,因此加入同步锁以避免在该线程没有完成操作之前,被其他线程的调用,     从而保证了该变量的唯一性和准确性。
Differences between synchronization methods and synchronized code blocks
    同步方法使用synchronize修饰方法,在调用该代码块时,需要获得内置锁(java对象都有一个内置锁,否则就处于阻塞状态)内置锁会保护整个方法。在调用该方法前,需要获得内置锁,否则就处于阻塞状态。    2.同步代码块使用synchronized(object){}进行修饰,在调用该代码块时,需要获得内置锁,否则就处于阻塞状态 代码如: synchronized(object){             //内容          }
Java reflection mechanism
反射的概述Reflection    JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。要想解剖一个类,必须先要获取到该类的字节码文件对象。而解剖使用的就是Class类中的方法.所以先要获取到每一个字节码文件对应的Class类型的对象.    1.字节码。所谓的字节码就是当java虚拟机载入某个类的对象时,首先须要将硬盘中该类的源码编译成class文件的二进制代码(字节码),然后将class文件的字节码载入到内存中,之后再创建该类的对象    2.java反射的基础是Class类,Class类实例代表着内中中的一份字节码。    
Reflection Example
package fanshe;/** * 获取Class对象的三种方式 * 1 Object ——> getClass(); * 2 任何数据类型(包括基本数据类型)都有一个“静态”的class属性 * 3 通过Class类的静态方法:forName(String  className)(常用) * */public class Fanshe {    public static void main(String[] args) {        //第一种方式获取Class对象          Student stu1 = new Student();//这一new 产生一个Student对象,一个Class对象。        Class stuClass = stu1.getClass();//获取Class对象        System.out.println(stuClass.getName());                //第二种方式获取Class对象        Class stuClass2 = Student.class;        System.out.println(stuClass == stuClass2);//判断第一种方式获取的Class对象和第二种方式获取的是否是同一个                //第三种方式获取Class对象 (常用)        try {            Class stuClass3 = Class.forName("fanshe.Student");//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名            System.out.println(stuClass3 == stuClass2);//判断三种方式是否获取的是同一个Class对象        } catch (ClassNotFoundException e) {            e.printStackTrace();        }            }}注意:在运行期间,只能有一个Class对象产生
What is the difference between Reflection and introspection in Java?
说起反射,还有一个相似的概念 ‘Introspection’,字面意思是“自省、内省”,它们之间的区别如下:内省      在运行时检查一个对象的类型或者属性     最常见的例子就是运行时通过 a instanceof A 来判断 a 对象的类型反射      用来在运行时检查或者修改一个对象信息     可以用来实现看似不可能的操作,比如访问私有方法,动态创建对象     可以看到,反射是在内省的基础上,增加了修改的能力。
Gets the construction method through reflection and uses the
Package fanshe; public class Student {//---------------construction Method-------------------//(default constructor) Student (String str) {Syste    M.out.println ("(default) construction method s =" + str); }//Non-parametric construction method public Student () {System.out.println ("The call has been made to the common, parameterless construction method performed ...    ");    }//has a constructor for a parameter public Student (char name) {System.out.println ("name:" + name); }//constructor with multiple arguments public Student (String name, Int. age) {System.out.println ("Name:" +name+ "Ages:" + ");    Solve the problem later.    }//Protected construction Method protected Student (Boolean N) {System.out.println ("protected construction method n =" + N);    }//Private construction method Student (int age) {System.out.println ("Private construction Method Ages:" + aged); }} Test class package fanshe;            Import java.lang.reflect.constructor;/* A Class object to get the constructor method, member variable, member method, and access member; 1. Get the constructor method: 1). Batch method: Public constructor[] GetConstructors (): All publicly constructed methods, common constructor[] getdeclaredconstructors (): Gets all the constructor methods, including Private, protected, default, public) 2). Gets a single method and calls: Public Constructor getconstructor (Class ... parametertypes): Gets a single "common" construction method: Publicly Con Structor getdeclaredconstructor (Class ... parametertypes): Gets the "a constructor method" can be private, or protected, default, public; constructor--> Newinstance (Object ... initargs) */public class Constructors {public static void main (string[] args) throws Exception {//1. Load class object class Clazz = Class.forName ("Fanshe.                        Student ");        2. Obtain all public construction method System.out.println ("********************** All public construction Method *********************************");        constructor[] ConArray = Clazz.getconstructors ();        for (Constructor C:conarray) {System.out.println (c);        } System.out.println ("************ all construction methods (including: private, protected, default, public) ***************");        ConArray = Clazz.getdeclaredconstructors ();        for (Constructor C:conarray) {System.out.println (c); } System.out.println ("***************** gets public,Non-parametric construction method ******************************* ");        Constructor con = clazz.getconstructor (null);            1>, because it is an argument-free construction method, the type is a null, not write: It is required to be a type of parameter, remember that the type//2>, return is the class object that describes the parameterless constructor.        System.out.println ("con =" + con);    Call construction method Object obj = Con.newinstance ();    System.out.println ("obj =" + obj);                Student stu = (Student) obj;        System.out.println ("****************** Gets the private constructor method and calls *******************************");        con = clazz.getdeclaredconstructor (char.class);        System.out.println (con);    Call construction Method Con.setaccessible (TRUE);//violent access (ignoring the access modifier) obj = con.newinstance (' Male '); }    }
Gets the method of reflection.
public static void main(String[] args) throws Exception {        String s1 = "hello";        //參数为函数名,函数的參数(可变长)        Method m = s1.getClass().getMethod("charAt", int.class);        //參数为要调用的对象,以及函数的參数。这里假设第一个參数为null,表示调用的是类的静态方法        System.out.println(m.invoke(s1, 1));    }

2018.8.1 reflection and synchronization in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.