Java class中getFields、getConstructors、getMethods什么作用

1.getFields、getConstructors、getMethods获取的分别是一个class里面的public 变量、构造器、方法。

另外还有一种是相似方法(是否含有Declared)

public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法
public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法
package priv.whh.edu.demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Pattern;


public class Demo {
	
	 private int a;  
     
	    float b;  
	      
	    protected double c;  
	      
	    public long d;  
	      
	    private void print(){  
	          
	    }  
	      
	    void print(int a){  
	          
	    }  
	      
	    protected void print(float a){  
	          
	    }  
	      
	    public void print(double a){  
	          
	    }  
	      public static void main(String[] args)throws ClassNotFoundException { 
	    	  //正则表达式去掉(变量、方法、构造器)前缀的包名
	    	 Pattern compile = Pattern.compile("\\w+\\.");
	    	 Class<?> forName = Class.forName("priv.whh.edu.demo.Demo");
	    	 System.out.println("-------------------------------------");
	    	 Field[] fields = forName.getFields();
	    	 System.out.println(fields[0].toString());
	    	 for(Field field:fields){
	    		 System.out.println(compile.matcher(field.toString()).replaceAll(""));
	    	 }
	    	 System.out.println("-------------------------------------");
	    	 Constructor[] constructors = forName.getConstructors();
	    	 for(Constructor constructor:constructors){
	    		 System.out.println(compile.matcher(constructor.toString()).replaceAll(""));
	    	 }
	    	 System.out.println("-------------------------------------");
	    	 Method[] methods = forName.getMethods();    	 
	    	 for(Method method:methods){  
	    		 System.out.println(compile.matcher(method.toString()).replaceAll(""));    	 
	    		 }  	     	 
	    	 }  
}/*output:
-------------------------------------
public long priv.whh.edu.demo.Demo.d
public long d
-------------------------------------
public Demo()
-------------------------------------
public static void main(String[]) throws ClassNotFoundException
public void print(double)
public final void wait() throws InterruptedException
public final void wait(long,int) throws InterruptedException
public final native void wait(long) throws InterruptedException
public native int hashCode()
public final native Class getClass()
public boolean equals(Object)
public String toString()
public final native void notify()
public final native void notifyAll()

*/

猜你喜欢

转载自blog.csdn.net/qq_32589355/article/details/80170786