A simple example of a private method using reflection to invoke another class in Java _java

Source: Internet
Author: User
Tags reflection

We know that a Java application cannot access the private method of a persisted class, but Hibernate does not have this restriction to access various levels of methods, such as private, default, protected, public. How does hibernate implement this function? The answer is to use the Java reflection mechanism as follows:

Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
public class Reflectdemo {public
	static void Main (string[] args) throws Exception {Method method
		= Packageclazz. Class.getdeclaredmethod ("Privilegedmethod", New Class[]{string.class,string.class});  
		Method.setaccessible (true);
		Method.invoke (New Packageclazz (), "452345234", "q31234132");
	}

Class Packageclazz {
	private void Privilegedmethod (String invokername,string adb) {
		System.out.println ("--- "+invokername+"----"+adb)";
	}

The output is:---452345234----q31234132

We see that using the reflection mechanism of Java, even private methods can be invoked to use. But I came up with a question--that the private method can be invoked, what's the point of encapsulation?

The above Java in the use of reflection to invoke another kind of private method of a simple example is the small series to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

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.