• java中的反射机制


    一、java中获取java.lang.class对象操作方法

      1. 可以利用Class.forName("类的全路径")

      2. this.getClass()  //得到的是正在被调用的类

      3.对象.class

    这三种方法获取的结果都是Class对象

    二、关于反射的知识强化one

    public class Test {
        public static void A1() {}
        public void A2() {}
        private void B1() {}
        private static void B2() {}
        public static void main(String[] args) {
            Class clazz = Test.class;
            System.out.println("clazz: "+clazz);//返回的Map集合
            System.out.println("clazz.getName(): "+clazz.getName());
            System.out.println("clazz.getSimpleName(): "+clazz.getSimpleName());
            for(Method method:clazz.getMethods()) {
                //数组类返回从 Object 类继承的所有(公共)member 方法(包括Object的方法)
                System.out.println("clazz.getMethods(): "+method.getName());
            }
        }
    }

    结果:

      强化只是two:

    public class A {
        public A() {
            Class clazz = this.getClass();
            System.out.println(clazz);
        }
    }
    public class B extends A{
        public static void main(String[] args) {
            //new B
            B b = new B();//new B的时候会调用A的构造
            //new A
            A a = new A();
        }
    }

     结果:

    三、利用反射执行方法Method

    import java.lang.reflect.Method;
    
    public class TestClassLoad {
      public static void main(String[] args) throws Exception {
        Class<?> clz = Class.forName("A");
        Object o = clz.newInstance();
        Method m = clz.getMethod("foo", String.class);
        for (int i = 0; i < 16; i++) {
          m.invoke(o, Integer.toString(i));
        }
      }
    }
    

      上面程序中可以将clz换为this.getClass()来执行获取Method对象,invoke(类对象,方法参数)

    四、根据配置文件执行不同的类

    public class Factory {
        private static Properties props;
    
        static {
        	System.out.println("静态代码块");
        	props = new Properties();
            try {
                props.load(new FileInputStream("./src/main/resources/config.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        {
        	System.out.println("非静态代码块");
        }
        public static User getUserInstance() throws Exception{
        	return (User) Class.forName(props.getProperty("user")).newInstance();
        }
        public static Car getCarInstance() throws Exception{
        	return (Car) Class.forName(props.getProperty("car")).newInstance();
        }
    }

    config.properties配置文件内容为:

    user=com.it.entity.User
    car=com.it.entity.Car

    value的值是类的全路径

    五、可以利用java的反射机制来实现Servlet的抽取

    package com.iang.web.servlet.base;
    
    import java.io.IOException;
    import java.lang.reflect.Method;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    public class BaseServlet extends HttpServlet{
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	@Override
    	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		try {
    			//1.获取方法名称
    			String mName = request.getParameter("op");
    			
    			//1.1判断method参数是否为空,若为空执行默认的方法
    			if(mName == null || mName.trim().length()==0) {
    				mName = "index";
    			}
    			//2.获取方法对象
    			Method method=this.getClass().getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
    		
    			//3.让方法执行,接受返回值
    			String path=(String) method.invoke(this, request,response);
    			
    			//4.判断返回值是否为空,若不为空统一处理请求转发
    			if(path!=null)
    			{
    				request.getRequestDispatcher(path).forward(request, response);
    			}
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			throw new RuntimeException();
    		} 
    		
    	}
    	
    	public String index(HttpServletRequest request, HttpServletResponse response) throws IOException {
    		response.setContentType("text/html;charset=utf-8");
    		response.getWriter().println("亲不要捣乱");
    		return null;
    	}
    }
    

      下面是一个例子:

    package com.iang.web.servlet;
    
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.itwang.domain.News;
    import com.itwang.domain.NewsCategory;
    import com.itwang.service.NewsBusinessService;
    import com.itwang.service.impl.NewsBusinessServiceImpl;
    import com.itwang.web.servlet.base.BaseServlet;
    
    /**
     * Servlet implementation class NewsManagerServlet
     */
    @WebServlet("/NewsManagerServlet")
    public class NewsManagerServlet extends BaseServlet {
    	private static final long serialVersionUID = 1L;
        private NewsBusinessService nbs = new NewsBusinessServiceImpl();
    
    
    	public String updateNews(HttpServletRequest request, HttpServletResponse response) {
    		// TODO Auto-generated method stub
    		String id=request.getParameter("id");
    		String title=request.getParameter("title");
    		String publicdate=request.getParameter("publicdate");
    		String content=request.getParameter("content");
    		String publicauthor=request.getParameter("publicauthor");
    		String keywords=request.getParameter("keywords");
    		String categoryid=request.getParameter("categoryid");
    		NewsCategory newsCategory=nbs.findNewsCategoryById(categoryid);
    		News news=new News();
    		news.setCategory(newsCategory);
    		news.setContent(content);
    		news.setKeywords(keywords);
    		news.setPublicauthor(publicauthor);
    		news.setPublicdate(publicdate);
    		news.setTitle(title);
    		news.setId(id);
    		nbs.updateNews(news);
    		return null;
    	}
    
    	public String addNewsUI(HttpServletRequest request, HttpServletResponse response) {
    		// TODO Auto-generated method stub
    		List<NewsCategory> listNewsCategory=nbs.findAllNewsCategory();
    		request.setAttribute("listNewsCategory", listNewsCategory);
    		return "/admin/addNews.jsp";
    	}
    }
    
  • 相关阅读:
    JavaScript 简介
    数据库的链接语句
    sqlserver 大杂烩
    数据库操作
    Filter Big Picture
    struts2配置有命名空间的Action: 解决No configuration found for the specified action错误
    Firefox的Firebug调试
    jQuery判断元素显示或隐藏, is 函数
    Jsp Tag
    java revisit
  • 原文地址:https://www.cnblogs.com/ya-qiang/p/9320526.html
Copyright © 2020-2023  润新知