Java学习笔记之反射

以下是博主学java的时候记的一些笔记,分享给大家,如果有错误或者以为的话,可以在下方留言

 

反射

 

package com.fanshe;

 

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

 

public class Demo_3 {

 

@SuppressWarnings("unchecked")

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

//得到字节码文件

Class c1 = String.class.getClass();

System.out.println(c1);

System.out.println();

String str = "com.fanshe.Test";

Class c2 = Class.forName(str);

Object obj = c2.newInstance();

System.out.println(obj);

Class c3 = Class.forName("com.fanshe.Text");

//得到构造函数

Constructor constructor = c3.getConstructor(int.class,int.class);

Object object = constructor.newInstance(3,8);

//得到类中的字段

Field[] field1 = null;

field1 = c3.getDeclaredFields();

for(Field field : field1){

System.out.println(field);

}

System.out.println(field1);

System.out.println();

//得到类中的方法

Method method = null;

method = c3.getDeclaredMethod("x", null);

Object no = c3.newInstance();

method.invoke(no, null);

method.invoke(object, null);

// Constructor constructor = c2.getConstructor(int.class,int.class);

// Object bon = constructor.newInstance(12,23);

 

}

 

}

 

 

 

:

package com.fanshe;

 

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.util.HashMap;

import java.util.Map.Entry;

import java.util.Vector;

 

public class Demo_2 {

 

public static void main(String[] args)  throws Exception{

// TODO Auto-generated method stub

Text text = new Text(3,5);

Field fileX = text.getClass().getField("x");           //代表一个类里面的一个变量,并不代表具体的值

System.out.println(fileX.get(text));

Field fileY = text.getClass().getDeclaredField("y");

fileY.setAccessible(true);

System.out.println(fileY.get(text));

Test te1= new Test();

te1.getN();

}

}

class Text{

public int x;

public int y;

public Text(){

}

public Text(int x,int y){

this.x = x;

this.y = y;

}

public void x(){

System.out.println("x的值:"+x+" y的值:"+y);

}

}

 

答案:

<span style="font-size:18px;">3

5

反射</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值