zoukankan      html  css  js  c++  java
  • 反射

     1 package com.lxj.demo;
     2 
     3 public class Boy {
     4     // 私有构造方法
     5     private Boy(){
     6         System.out.println("已经被实例化");
     7     }
     8     // 单例模式,在本类中私有化实现Boy对象(static)指唯一的
     9     private static Boy boy = new Boy();
    10     // 提供外界访问的方法,返回值是Boy
    11     public static Boy getInstance(){
    12         return boy;
    13         
    14     }
    15     // 私有成员方法meet
    16     private void meet(){
    17         System.out.println("踢足球");
    18     }
    19     // 私有属性
    20     private String name = "qinyu";
    21 }
     1 package com.lxj.demo;
     2 
     3 import java.lang.reflect.Constructor;
     4 import java.lang.reflect.Field;
     5 import java.lang.reflect.Method;
     6 
     7 public class Demo {
     8     public static void main(String[] args) {
     9         try {
    10             // 加载类。这里的?是一个占位符的意思。boyClass是保存加载类的所有信息
    11             Class<?> boyClass = Class.forName("com.lxj.demo.Boy");
    12             // constructor表示保存构造方法的信息
    13             Constructor<?> constructor = boyClass.getDeclaredConstructor();
    14             // 设置constructor的访问性
    15             constructor.setAccessible(true);
    16             // 实例化boy对象
    17             Boy boy = (Boy) constructor.newInstance();
    18             // tMethod表示保存成员方法的信息,拿到私有的成员方法meet
    19             Method tMethod = boyClass.getDeclaredMethod("meet");
    20             // 设置tMethod的访问性
    21             tMethod.setAccessible(true);
    22             // 通过tMethod来调用boy对象的meet方法
    23             tMethod.invoke(boy);
    24             // field表示保存成员变量(属性),拿到了私有的属性name
    25             Field field = boyClass.getDeclaredField("name");
    26             // 设置field的访问性
    27             field.setAccessible(true);
    28             // 调用boy对象里面的成员属性强转成string类型
    29             String name = (String) field.get(boy);
    30             // 打印出成员属性的值
    31             System.out.println(name);
    32         } catch (Exception e) {
    33             // TODO Auto-generated catch block
    34             e.printStackTrace();
    35         }
    36     }
    37 }
  • 相关阅读:
    hdu 2019 数列有序!
    hdu 2023 求平均成绩
    HDU 5805 NanoApe Loves Sequence (思维题) BestCoder Round #86 1002
    51nod 1264 线段相交
    Gym 100801A Alex Origami Squares (求正方形边长)
    HDU 5512 Pagodas (gcd)
    HDU 5510 Bazinga (字符串匹配)
    UVALive 7269 Snake Carpet (构造)
    UVALive 7270 Osu! Master (阅读理解题)
    UVALive 7267 Mysterious Antiques in Sackler Museum (判断长方形)
  • 原文地址:https://www.cnblogs.com/lxjhoney/p/6406407.html
Copyright © 2011-2022 走看看