JAVA Reflection

1、A instruction about JAVA REFLECTION

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

  The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.

  One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.

2、Some Usage of  API

1)get class

  A.getClass()

  i.Stringstr="abc";
  ii.Classc1=str.getClass();

  B.Class.forName()(staticmethod)

  i.Classc1=Class.forName("java.lang.String");
  ii.Classc2=Class.forName("java.awt.Button");

  C..class

  i.Classc1=String.class;
  ii.Classc2=java.awt.Button.class;
  iii.Classc4=int.class;
  iv.Classc5=int[].class;

  D.TYPE(primitivewrapperclasses)

  i.Classc1=Boolean.TYPE;

  2)get attributes

  see Java.lang.class

Public  Field  getField

(String name)

return  Field mumber,show public only

public Field[] getFields()

return array of Field object,only show public

Public  Field

getDeclaredField(String name)

return a  Field object,show all,include these private ones.

public  Field[]

getDeclaredFields()

...

  3)get method


public  Method

getMethod(String name,

... )

return a  Method object,show public.

public Method[] getMethods()

public Method

getDeclaredMethod(String name,…)

public Method[]

getDeclaredMethods()

show all

  4)get constructor


public  Constructor

getConstructor(Class<?>... )

return a Constructor object

public  Constructor<?>[]

getConstructors()

Public  Constructor<T>

getDeclaredConstructor(Class<?>...)

public  Constructor<?>[]

getDeclaredConstructors()

3、A demo about JAVA REFLECTION

Test.java

package com.demo.classes;

public class Test {
	public int mCount = 0;
	private String str = null;
	
	public Test() {
		
	}
	
	public Test(int m) {
		this.mCount = m;
	}
	
	public Test(String str) {
		this.str = str;
	}
	
	public Test(String s1, String s2) {
		this.str = s1;
	}
	
	private Test(Long mCount) {
		
	}
	
	public void fun() {
		System.out.println("Test:fun()");
	}
	
	public void foo() {
		System.out.println("Test:foo()");
	}
	
	public void test(String str) {
		System.out.print("Test:test()=>" + str);
	}
	
	private void privatef() {
		System.out.print("Test:private()");
	}
}

TestReflection.java

package com.demo.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestReflection {

	public static void main(String[] args) {
		String str = new String("java.lang.String");
		try {
			
			/*
			 * get the ClassType & Constructor
			 */
			System.out.println("\n----------TEST ABOUT ClassType---------------");
			Class classType = Class.forName(str);
			Constructor constructor = classType.getConstructor();
			System.out.println(constructor.toString());
			
			/*
			 * get the specific method of specific class,
			 * and then invoke these methods.
			 */
			String className = "com.demo.classes.Test";
			String[] methodName = {"fun", "foo", "test", "privatef"};
			classType = Class.forName(className);
			Object obj = classType.newInstance();
			System.out.println(obj);
			
			System.out.println("\n----------TEST ABOUT CONSTRUCTORS---------------");
			Constructor[] constructors = classType.getConstructors();
			for (Constructor con : constructors) {
				System.out.println("Constructor : " + con.toString());
			}
			
			/*
			 * compare with the function <getConstructors>,
			 * this <getDeclaredConstructors> can get all constructor,
			 * include the private ones. 
			 */
			constructors = classType.getDeclaredConstructors();
			for (Constructor con : constructors) {
				System.out.println("Constructor : " + con.toString());
			}
			
			/*
			 * we can get the function by specific class type.
			 */
			Constructor con = classType.getConstructor(null);
			System.out.println(con.toString());
			con = classType.getConstructor(String.class);
			System.out.println(con.toString());
			con = classType.getConstructor(int.class);
			System.out.println(con.toString());
			con = classType.getConstructor(String.class, String.class);
			System.out.println(con.toString());
			
					
			/*
			 * 
			 */
			System.out.println("\n----------TEST ABOUT Field---------------");
			Field field = classType.getField("mCount");
			System.out.println(field.toString());
			Field[] fields = classType.getDeclaredFields();
			for (Field f : fields) {
				System.out.println(" Field : " + f.toString());
			}
			
			System.out.println("\n----------TEST ABOUT Methods---------------");
			//invoke fun()
			Method method = classType.getMethod(methodName[0], null);
			method.invoke(obj, null);
			//invoke foo()
			method = classType.getMethod(methodName[1], null);
			method.invoke(obj, null);
			//invoke test function
			method = classType.getDeclaredMethod(methodName[2], String.class);
			method.invoke(obj, "hello");
			//invoke private function
			method = classType.getDeclaredMethod(methodName[3], null);
			//method.invoke(obj, null); //excpetion,private function can't be invoked!
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值