<pre name="code" class="java">import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method; class Point{
int x;
private int y; public Point(){
x = 1;
y = 2;
} public void setX(int x) {
this.x = x;
} public void setY(int y) {
this.y = y;
} private Point(int x){
this();
this.x = x;
} public Point(int x, int y) {
super();
this.x = x;
this.y = y;
} public void printPoint(){
System.out.println("x = " + x + " , y = " + y);
}
} public class ReflectTest2 { public static void main(String[] args) throws Exception { //使用第一种方法创建对象
Class cls1 = Class.forName("Point");
Constructor con1 = cls1.getConstructor(int.class,int.class);
Point p1 = (Point) con1.newInstance(5,6);
p1.printPoint(); //使用另外一种方法创建对象
Class cls2 = Point.class;
Point p2 = (Point) cls2.newInstance();//无參构造函数
p2.printPoint(); //使用第三种方法创建对象
Class cls3 = p1.getClass();
//使用p1对象的setX方法将x值改动为10
Method m1 = cls3.getMethod("setX", int.class);
m1.invoke(p1, 10);
p1.printPoint(); /*
* Note:
* getDeclaredConstructor能够返回指定參数的构造函数,
* 而getConstructor仅仅能放回指定參数的public的构造函数
* */
Constructor con2 = cls3.getDeclaredConstructor(int.class);
//訪问私有变量、函数须要设置accessible
con2.setAccessible(true);
Point p4 = (Point) con2.newInstance(3);
p4.printPoint(); //Field f1 = cls3.getField("y");//error
Field f1 = cls3.getDeclaredField("y");
f1.setAccessible(true);
//获取p1的y值
System.out.println(f1.get(p1));
} }

最新文章

  1. 使用C#开发计划任务调度服务
  2. 【经验之谈】前端面试知识点总结03(JavaScript相关)——附答案
  3. Android学习笔记——button_activity
  4. [团队项目]----Math Calculator
  5. java中的基本数据类型存放位置
  6. 把硬盘格式化成ext格式的cpu占用率就下来了
  7. #BeginLibraryItem 的疑问...
  8. android 数据共享
  9. CSU 1811 Tree Intersection
  10. 8.多线程和Socket通信
  11. AugularJS从入门到实践(一)
  12. 巩固java(三)---java修饰符
  13. WEB网站类型系统中使用的OFFICE控件
  14. 文件缓存tmpfs简单使用
  15. vsftpd中配置文件详解
  16. BZOJ2821 作诗(Poetize) 分块
  17. c# 通过GroupBy 进行分组
  18. ArcEngine应用程序中无法实现TOC图层多选
  19. Windows下Visual Studio 2013编译Lua 5.2.3
  20. 【Python 开发】第二篇 :Python安装

热门文章

  1. laravel 5.5 项目报错
  2. 【BZOJ3730】震波 - 动态点分治
  3. SP687 REPEATS - Repeats(后缀数组)
  4. CF1005F Berland and the Shortest Paths (树上构造最短路树)
  5. django 开发之给admin 模块添加富文本编辑器
  6. 普通码农和CTO之间的差距
  7. 榨取kkksc03 luogu1855 dp 裸二维费用背包
  8. mysql-数据库维护
  9. IBM主机上清除告警黄灯方法
  10. Out-of-Process iframes (OOPIFs)