以下是博主学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>