Java Conditional Compile - Java条件编译

本文介绍了一种用于可选地从类的编译版本中移除代码片段的条件编译实践。通过定义静态最终布尔值并根据其真假来控制代码块是否被编译,这种方法常用于实现调试语句、日志记录和断言。
The conditional compilation practice is used to optionally remove chunks of code from the compiled version of a class. It uses the fact that compilers will ignore any unreachable branches of code. 

To implement conditional compilation, 

* define a static final boolean value as a non-private member of some class 
* place code which is to be conditionally compiled in an if block which evaluates the boolean 
* set the value of the boolean to false to cause the compiler to ignore the branch; otherwise, keep its value as true 

This practice is used mostly for implementing debugging statements, logging statements, and for assertions. With the advent of assert and the Logging API in JDK 1.4, the utility of conditional compilation is probably reduced. 

Example 
public final class Debug {
  
//set to false to allow compiler to identify and eliminate
  
//unreachable code
  public static final boolean ON = true;




import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

/**
* Uses conditional compilation to optionally print debugging statements.
*/public final class GenericServlet extends HttpServlet {

  
public void init(ServletConfig aConfig) throws ServletException {
    
super.init(aConfig);

    
//print out a message, but only if Debug.ON evaluates to true
    
//if Debug.ON evaluates to false, this entire block of code will be
    
//passed over by the compiler, and will not be present in output .class file
    if (Debug.ON) {
      System.out.println(
"**** INIT OF My Controller *****");
    }
  }

  
public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse)
                                              
throws ServletException, IOException {
    
if (Debug.ON) {
      System.out.println(
"Processing doGet");
    }
    doHttpRequest(aRequest, aResponse);
  }

  
public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse)
                                              
throws ServletException, IOException {
    
if (Debug.ON) {
      System.out.println(
"Processing doPost");
    }
    doHttpRequest(aRequest, aResponse);
  }

  
/// PRIVATE /////

  
private void doHttpRequest(HttpServletRequest aRequest, HttpServletResponse aResponse)
                                              
throws ServletException, IOException {
     
//empty
  }

}

 

 

转载于:https://www.cnblogs.com/super119/archive/2011/01/03/1924544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值