Java学習ノートの反射

2165 ワード

以下はブロガーが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);

}

}

 
答え:
3

5