javaee 反射应用之一,指定构造函数创建对象

package com.test.classobject;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.pojo.Student;

/**
 * Servlet implementation class TestServlet2
 */
@WebServlet("/TestServlet2")
public class TestServlet2 extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet2() {
    
    
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		//反射用法1
				try {
    
    
					Class clazz1=Class.forName("com.test.pojo.Student");
					
					//根据参数列表获得指定的构造函数
					Constructor constructor= clazz1.getDeclaredConstructor(String.class,int.class);
					
					//根据构造函数创建对象
					Student student=(Student) constructor.newInstance("zhangsan",23);
					
					response.getWriter().println(student.getSname());
					
					//获得所有的构造函数 
					Constructor[] arr= clazz1.getDeclaredConstructors();
					
					for(Constructor constructor2 : arr)
					{
    
    
						//获得构造函数的参数类型
						Class[] brr=  constructor2.getParameterTypes();
						
						for(Class clazz2:brr)
							 response.getWriter().print(clazz2.getName()+",");
						
						response.getWriter().println();
					}
					
					
				} catch (ClassNotFoundException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstantiationException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

猜你喜欢

转载自blog.csdn.net/Rockandrollman/article/details/131737157