JAVA_Reflection1
package com.qf.reflection1; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method; class Student {
private String name;
private int age; public String getName() {
return name;
} private void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Student(String name, int age) {
super();
this.name = name;
this.age = age;
} public Student() {
super();
} } public class Test { public static void main(String[] args) { try {
// 使用反射第一步 得到某个类的Class对象
Class<Student> clazz1 = Student.class;
Class<?> clazz2 = Class.forName("com.qf.reflection1.Student");
Student student = new Student();
Class<?> clazz3 = student.getClass(); System.out.println("访问类所有属性");
// clazz1.getDeclaredField("age");// 根据属性名 得到属性值 私有的也能得到
// clazz1.getField("name");// 只能得到有访问权限的指定属性
// clazz1.getFields();//得到有访问权限的所有属性
Field fields[] = clazz1.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
} // 通过反射创建Student对象
// 1,得到无参构造方法
Constructor<Student> constructor = clazz1.getConstructor();
// 2,创建对象
Student stu = constructor.newInstance();
// 等价于 Student stu = new Student(); // 调用setName
// 1,得到setName()
Method method = clazz1.getDeclaredMethod("setName", new Class[] { String.class });
// 私有方法需要设置访问权限
method.setAccessible(true);
// 2,通过之前的student对象调用setName表示的方法
method.invoke(stu, new Object[] { "尼古拉斯赵四" }); // 1,得到getName()
Method getName = clazz1.getDeclaredMethod("getName", new Class[] {});
// 2,通过之前的student对象调用getName表示的方法
Object object = getName.invoke(stu, new Object[] {});
System.out.println(object); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
JAVA_Reflection1的更多相关文章
随机推荐
- .Net课程体系
.Net课程体系
- put a ContextMenu into the header of a TabPage z
publicclassMyTabControl:TabControl { protected override void OnMouseUp(MouseEventArgs e){ if(e.Butto ...
- POJ 2486-Apple Tree(树状背包)
题意 n个节点的树,每个节点都有价值,求在树上最多走k步获得的最大价值(从1开始走,节点的价值只能获取一次) 分析: 开始以为是最基础的树形背包,但后来发现,不能只走子树,有可能还回到根节点,dp[i ...
- Ajax异步请求-简单模版
<script type="text/javascript"> window.onload = function () { document.getElementByI ...
- (Trie) uvalive 3942 Remember the word
题意:告诉你一个母串和子串,能用多少种不同的方案组合出母串. 思路:字典树(显然)+DP DP: dp[i]+=dp[j+1] i<=j<=m-1,且i到j的字符串能在字典树中找到.也就 ...
- jenkins api调用
在使用jenkins的时候,有时候需要其他外部调用,下面是调用方法,不定期更新 job调用 使用user和password: curl -X POST "jobPath/buildWithP ...
- CentOS 6.5 安装配置VSFTP
1.下载安装VSFTP 首先查看当前系统是否已经安装VSFTP,若未安装则使用yum安装. chkconfig --list | grep vsftpd #查看是否安装 yum install vsf ...
- HDU2686-Matrix & HDU3376-Matrix Again(费用流)
比较简单的题了. 只需从左上角到右下角找两条路就可以了. 因为每个点只能走一次,所以拆点,限制流量为1. 因为求的是最大值,所以权值取反求最小值. 因为第一个点和最后一个点经过两次,只算一次,最后要减 ...
- PT100测温函数
PT100电阻值计算过程如下: 理论电压关系为:V3-V1=11(V2-V1).由于电阻等的误差原因,采用实际测量求平均值的方法得出实际放大倍数. 放大电路测量几组数据如下:其中V3-V1=Av(V2 ...
- 超级MINI STLINK V2 官方固件自动升级 ST-Link 【worldsing 笔记】
简介: 支持所有带SWIM接口的STM8系列单片机 支持所有带SWD接口的STM32系列单片机 完全兼容Keil,STVP,STVD,IAR,COSMIC,STM32 ST-LINK Utility! ...