首页 > 其他分享 >466Class对象功能_获取Constructor和467反射_Class对象功能_获取Method

466Class对象功能_获取Constructor和467反射_Class对象功能_获取Method

时间:2022-09-26 15:46:12浏览次数:50  
标签:466Class 467 System Class 获取 Constructor println Method out

Class对象功能_获取Constructor

Constructor<?>[] getConstructors()

Constructor<T> getConstructor(Class<?>... parameterTypes)

 

Constructor<?>[] getDeclaredConstructors()

Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)

 

Constructor构造方法

创建对象:

T newInstance(Object... initargs)

如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法

 

 

忽略访问权限修饰符的安全检查 setAccessible(true):暴力反射

import domain.Person;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
 
public class ReflectDemo3 {
    public static void main(String[] args) throws Exception {
 
        //0、获取Person的Class对象
        Class personClass = Person.class;
 
        //Constructor<?>[] getConstructors()
        Constructor constructor = personClass.getConstructor(String.class,int.class);
        System.out.println(constructor);
        //创建对象
        Object person = constructor.newInstance("张三", 23);
        System.out.println(person);
 
        System.out.println("--------");
 
        Constructor constructor1 = personClass.getConstructor();
        System.out.println(constructor1);
        //创建对象
        Object person1 = constructor1.newInstance();
        System.out.println(person1);
 
        Object o = personClass.getConstructor().newInstance();
        System.out.println(o);
    }
}

 

 

运行结果:

 

 

反射_Class对象功能_获取Method

Method[] getMethods()

Method getMethod(String name, Class<?>... parameterTypes)

 

Method[] getDeclaredMethods()

Method getDeclaredMethod(String name, Class<?>... parameterTypes)

 

Method :方法对象:

执行方法:

Object invoke(Object obj,Object... args)

获取方法名称:

String getName:获取方法名

import domain.Person;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
public class ReflectDemo4 {
    public static void main(String[] args) throws Exception {
 
        //0、获取Person的Class对象
        Class personClass = Person.class;
 
        //获取成员方法
        Method eat_method = personClass.getMethod("eat");
        Person p = new Person();
        //执行方法
        eat_method.invoke(p);
 
        Method eat_method2 = personClass.getMethod("eat", String.class);
        //执行方法
        eat_method2.invoke(p,"饭");
 
        System.out.println("-------------");
        //获取所有public修饰的方法
        Method[] methods = personClass.getMethods();
        for(Method method : methods){
            System.out.println(method);
            String name = method.getName();
            System.out.println(name);
        }
    }
}

 

运行结果:

标签:466Class,467,System,Class,获取,Constructor,println,Method,out
From: https://www.cnblogs.com/agzq/p/16729801.html

相关文章