关于在java中定义常量 和加log4j

http://www.blogjava.net/SmileFace/archive/2006/12/21/89179.html

首先:java没有叫 全局变量 的东西(有全局变量还叫OO吗?);原因:Java将所有设计都基于对象的基础上。Java的全局变量只能对一个类内部而言。能够在类内的任何地方使用的变量就是全局变量,而只在某个特定的函数或者局部的程序块内使用的变量则是局部变量。

所以:声明为static的变量实质上就是全局变量。当声明一个对象时,并不产生static变量的拷贝,而是该类所有的实例变量共用同一个static变量。

使用:java中只有static和非static变量,这个属于每个类的,如果需要全局变量比如PI(3.14...),可以写一个类Math,定义static变量PI,调用Math.PI就可以使用了,这样就达到我们使用全局变量的目的了。



1、将一个 package 中需要的常量集中到一个 XyzConstants 之类的 interface 里声明,
就像普通的 field 那样声明就行了。
public interface SomeConstants {
   public intPORT = 80;
   public String IP = "166.111.16.1";
   public boolean test = true;
} 就可以。
用到常量的类 implements 这个接口 .. 简单情况这样就行乐。

2、更 formal 的做法是写一个类维护所有的常量,负责从配置文件(例如properties文件或xml文件)读取所有的常量的值。
可以在一个 static {} 块里从配置文件中初始化所有 static 的变量。 这样有利于提高软件的可配置性。改些东东不用动代码,比较好。
最好要有 config Tool 负责写配置文件。

3.其他说明:

定义一个公开类,在里面加static 变量。
public class infos{
  private infos(){
  }
   public static int PORT = 80;
   public static String IP = "166.111.166.111";
   public static boolean test = true;
   public static finale String MYNAME="zzz"; //定义中用了finale,就是不能改变指的。
}
在别的class中调用这些变量就是: infos.PORT,infos.IP,infos.test,infos.MYNAME
多个class交互时可以通过改变这些变量的值来传递信息。比如 infos.test被别的class改成了false,可能表示某一件事已经失败或已经做过,其它class就可以提前知道这些信息。


Log4J Logging Inside Eclipse Console 

We use Apache Log4J for performing Logging at runtime for debugging Java Application. Eclipse is widely used IDE in Java Development environment, so it becomes essential to monitor the logs getting generated while writing java code in eclipse itself. To achieve this following steps need to taken.

1) Goto Package Explorer
This can be done by clicking on Window Menu, Click on Show view and select Package Explorer. Now you will see the Package Explorer window on the left screen/

2) Import Apache Log4J Library to Java Project
This can be achieve by right click the Java project, select Build Path and then Configure Build Path. Select Libraries Tab and click on Add External JAR’s. Now browse to the Log4J Library and click on OK.

3) Writing Java Code
To use Log4J package inside we need to import necessary Log4j classes. This can be achieved by writing following code.


import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
Example:


package com.test;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class test {
protected final static Logger log = Logger.getLogger(test.class);
public test() {
if(log.isDebugEnabled()) {
log.debug("Constructor Called For Test Function");
}
}

你可能感兴趣的:(log4j)