Java 反射 之 访问构造方法

http://www.verejava.com/?id=16995156772536

package com.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.TypeVariable;

public class TestConstructor
{
    public static void test()
    {
        try
        {
            Class c=Class.forName("com.entity.Student");
            Constructor[] constructors=c.getConstructors();
            for(Constructor constructor:constructors)
            {
                System.out.println(constructor.getModifiers());
                if(constructor.getModifiers()==Modifier.PUBLIC)
                {
                    System.out.println("public");
                }
                System.out.println(constructor.getName());
            }
        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        } 
    }
    public static void test2()
    {
        try
        {
            Class c=Class.forName("com.entity.Student");
            Constructor constructor=c.getConstructor(new Class[]{String.class,int.class});
            Object obj=constructor.newInstance(new Object[]{"李军",40});
            
        } catch (Exception e)
        {
            e.printStackTrace();
        } 
    }
    public static void main(String[] args)
    {
        test2();
    }
}





package com.entity;

public class Student
{
    private String name;
    private int age;
    
    public Student()
    {
        super();
        System.out.println("student");
    }
    public Student(String name, int age)
    {
        super();
        this.name = name;
        this.age = age;
        System.out.println(this.name+","+this.age);
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    
    
}

http://www.verejava.com/?id=16995156772536

猜你喜欢

转载自www.cnblogs.com/verejava/p/9232134.html