Java calls private methods of classes from outside

Source: Internet
Author: User

Considering that we have such a strange class: [java] package org. tsw; public class SecretTool {private SecretTool () {} private void myMotto () {System. out. println ("I like potato");} private int calculate (int left, int right) {return left + right;} There are two strange points: the first, this class displays the declaration of a private constructor (the compiler will not automatically add the default no-argument constructor). Normally, we cannot get an instance of it, even if we get an instance of it, we cannot use it either, because both of its methods are private. How can we call it? Reflection [java] public static void main (String [] args) throws Exception {Constructor <?> Constructor = SecretTool. class. getDeclaredConstructors () [0]; constructor. setAccessible (true); SecretTool tool = (SecretTool) constructor. newInstance (); // obtain an instance of the instance for (Method method: SecretTool. class. getDeclaredMethods () {method. setAccessible (true); if (method. getName (). equals ("mymoals") {method. invoke (tool); // call a private method without return values and parameters} else if (method. getName (). equals ("calculate") {Integer result = (Integer) method. invoke (tool, 1, 2); System. out. println ("1 + 2 =" + result. toString (); // The returned value of the call is an integer and the private method with the parameter }}} output: [plain] I like potato 1 + 2 = 3

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.