Rethinking java basics (2): Java reflection and java reflection

Source: Internet
Author: User

Rethinking java basics (2): Java reflection and java reflection
Let's take a look at Baidu's explanation: the JAVA reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known. For any object, can call any of its methods and attributes. This kind of information obtained dynamically and the function of dynamically calling methods of objects is called the reflection mechanism of java language. Let's take a look at the next example: this is the simplest method of reflection. Reflection is used to call class methods. The following is a reflection experiment: There are three kinds of humans (yellow, white, and black) inherited from the Human class, both of which have the common Human operation Behaviour.

/*** Behavior, which is different from animal * @ author tomsnail * @ date 10:10:42, January 1, April 1, 2015 */public interface Behaviour {public void eat (); public void sleep (); public void think (); public void sport (); public void work ();}
Import java. util. random;/*** skin type ** @ author tomsnail * @ date 11:41:33, December 11, April 1, 2015 */public enum SkinType {yellow, white, black; public static SkinType getSkinType () {int r = new Random (). nextInt (3); switch (r) {case 0: return SkinType. yellow; case 1: return SkinType. white; default: return SkinType. black ;}}}
Public abstract class Human implements Behaviour {private String name; private short age; private short sex; private SkinType skin; public String getName () {return name;} public void setName (String name) {this. name = name;} public short getAge () {return age;} public void setAge (short age) {this. age = age;} public short getSex () {return sex;} public void setSex (short sex) {this. sex = sex;} public SkinType getSkin () {return skin;} public void setSkin (SkinType skin) {this. skin = skin;}/*** the constructor uses skin color to distinguish different races. * @ author tomsnail * @ date 10:06:48, January 1, April 1, 2015 */public Human (SkinType skin) {this. skin = skin; this. name = skin. toString () + "_" + Goddess. counter ++ ;}}
Public class WhiteHuman extends Human {public WhiteHuman () {super (SkinType. white);} public WhiteHuman (SkinType skinType) {super (skinType); System. err. println ("I am white, I am") ;}@ Override public void eat () {System. err. println ("I am white, I am at eat") ;}@ Override public void sleep () {System. err. println ("I am white, I'm in sleep") ;}@ Override public void think () {System. err. println ("I am white, I am in think") ;}@ Override public void sport () {System. err. println ("I am white, I am in sport") ;}@ Override public void work () {System. err. println ("I am white, I am working");} private void selfMethod () {System. out. println ("this is a white private method ");}}
Public class YellowHuman extends Human {public YellowHuman () {super (SkinType. yellow);} public YellowHuman (SkinType skinType) {super (skinType); System. err. println ("I Am a yellow person, and my skin color is:" + skinType) ;}@ Override public void eat () {System. err. println ("I'm a yellow guy, I'm at eat") ;}@ Override public void sleep () {System. err. println ("I'm a yellow guy, I'm in sleep") ;}@ Override public void think () {System. err. println ("I Am a yellow man, I am in think") ;}@ Override public void sport () {System. err. println ("I'm a yellow man, I'm in sport") ;}@ Override public void work () {System. err. println ("I'm a yellow guy, I'm working");} private void selfMethod () {System. out. println ("this is a private method of the yellow race ");}}
Public class BlackHuman extends Human {public BlackHuman () {super (SkinType. black);} public BlackHuman (SkinType skinType) {super (skinType); System. err. println ("I am a black man, and my skin color is:" + skinType) ;}@ Override public void eat () {System. err. println ("I am a black man, I am at eat") ;}@ Override public void sleep () {System. err. println ("I am a black man, I'm in sleep") ;}@ Override public void think () {System. err. println ("I am a black man, I am in think") ;}@ Override public void sport () {System. err. println ("I am a black man, I am in sport") ;}@ Override public void work () {System. err. println ("I am a black man, I am working");} private void selfMethod () {System. out. println ("this is a black private method ");}}
/***** Nvwa * @ author tomsnail * @ date 10:20:16, January 1, April 1, 2015 */public class Goddess {public static int counter = 0; private static final String [] humanClasss = new String [] {"com. tomsnail. java. test. reflec. blackHuman "," com. tomsnail. java. test. reflec. whiteHuman "," com. tomsnail. java. test. reflec. yellowHuman "}; // private List of friends <Human> companions = new ArrayList <Human> (); private static final int number = 10; /*** create a person * @ author tomsnail * @ date 10:21:03, January 1, April 1, 2015 */public void createHuman () {int I = number; while (-- I> 0) {String className = randomHuman (); try {Class humanClass = Class. forName (className); Human human = null; if (System. currentTimeMillis () % I = 1) {System. out. println ("Create an unknown person in case of an accident"); Constructor constructor = humanClass. getConstructor (SkinType. class); // constructor. newInstance (SkinType. getSkinType (); // create an object through the constructor} else {System. out. println ("Create a nvwa" + humanClass. getSimpleName (); human = (Human) humanClass. newInstance ();} companions. add (human);} catch (Exception e) {e. printStackTrace () ;}} private String randomHuman () {int r = new Random (). nextInt (3); return humanClasss [r];}/*** life ** @ author tomsnail * @ date April 1, 2015 10:27:09 */public void life () throws Exception {while (true) {try {Thread. currentThread (). sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} Human human = companions. get (new Random (). nextInt (number-1); Class humanClass = human. getClass (); Field [] fs = humanClass. getSuperclass (). getDeclaredFields (); // parent class attribute for (Field f: fs) {System. out. println (f. getName () + ":" + humanClass. getMethod ("get" + getMethodName (f. getName ())). invoke (human, null); // print the parent class property value} Method [] MS = humanClass. getSuperclass (). getInterfaces () [0]. getMethods (); // obtain the interface Method m = MS [new Random (). nextInt (ms. length)]; m. invoke (human, null); // execute the interface Method pm = humanClass. getDeclaredMethod ("selfMethod"); // obtain the private method pm. setAccessible (true); // pm accessible. invoke (human, null ); // execute the private method}/*** change the first character to uppercase * @ author tomsnail * @ date 11:40:48 on January 1, April 1, 2015 */private static String getMethodName (String fildeName) throws Exception {byte [] items = fildeName. getBytes (); items [0] = (byte) (char) items [0]-'A' + 'A'); return new String (items );} public static void main (String [] args) throws Exception {Goddess goddess = new Goddess (); goddess. createHuman (); goddess. life ();}}
Nvwa created a YellowHuman nvwa and a BlackHuman nvwa and a WhiteHuman nvwa to create a WhiteHuman accident, create a person who doesn't know what, nvwa create a BlackHuman nvwa create a YellowHuman nvwa create a WhiteHuman I am black, my skin color is: yellow
Nvwa creates a WhiteHumanname: white_7age: 0sex: 0 skin: white. I am white.
This is the white private Method name: white_3age: 0sex: 0 skin: white I am white, I am in eat
This is the white private Method name: white_2 I am white, I am in workage: 0sex: 0 skin: white this is the white private Method name: yellow_0 I am a yellow, I am in thinkage: 0sex: 0 skin: yellow this is the private method of the yellow race name: black_1 I am black, I am working

 

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.