Simple example of Java reflection

Source: Internet
Author: User


Suppose you have the following classes:

Package com.test.reflect;

public class Person

{

private int age;

private String name;

Public Persion ()

{

}

Public persion (String name)

{

THIS.name = name;

}

Public Persion (String name,int Age)

{

This (name);

This.age = age;

}

public void SetName (String name)

{

THIS.name = name;

}

public void Setage (int.)

{

This.age = age;

}

@hide

public void SetAll (String name,int Age)

{

SetName (name);

Setage (age);

}

private int Getage ()

{

return age;

}


Public String GetName ()

{

return name;

}

}


Because Getage () and SetAll () are private methods and @hide annotations, normal objects cannot be called. In order to be able to use these two methods, it can be reflected by:

public class Reflectdemo

{

public static void Main (string[] args) throws Exception

{

Get class Reference

Class class = Class.forName ("com.test.reflect.Persion");

Instantiating a Person object

Persion persion = (persion) class.newinstance ();//persion parameterless constructor

Persion persion = (persion) class.newinstance ("Xiaoming", 20);

Get SetAll function

Method setAll = Class.getmethod ("SetAll", String.class,int.class);

Call the SetAll function

Setall.invoke (persion, "Xiaohong", 18);

Get Getage function

Method getage = Class.getmethod ("Getage");

Call the Getage function

int age = (int) getage.invoke (persion);

System.out.println ("Name:" +persion.getname () + "Age:" +age);

}

}



This article is from the "whatever957" blog, make sure to keep this source http://whatever957.blog.51cto.com/6835003/1794404

Simple example of Java reflection

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.