JAvaの基礎は日々蓄積されている



 
Eclipse version:
Eclipse Java EE IDE for Web Developers.
 
Version: Kepler Service Release 1
Build id: 20130919-0819
 
反射取得ターゲットclassのターゲット属性汎用実際のタイプ
(参考資料:Java反射とダイナミックエージェント):
 
 
package com.tch.test.testextend;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class GetGenericActualTypeTest {

    public static void main(String[] args) {
        getGenericActualType(User.class, "username");
        getGenericActualType(User.class, "friends");
        getGenericActualType(User.class, "friendUsername");
        getGenericActualType(User.class, "friendNameMap");
    }
    
    public static void getGenericActualType(Class<?> clazz, String fieldName){
        System.out.println("begin to getGenericActualType for field: " + fieldName);
        Field field = null;
        try {
            field = clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        if(field != null){
            /**
             *   field        ,     , getGenericType()   getType()     ,   field   
             *   field          , getGenericType()        ,       ParameterizedType,  getType()        
             */
            
            //          (  List<String> list,      String)
            Type genericType = field.getGenericType();
            // getType()          
            Type type = field.getType();
            System.out.println("fieldName: " + fieldName + ", genericType equals type? " + genericType.toString().equals(type.toString()));
            if(genericType instanceof ParameterizedType){
                //          
                Type[] actualTypes = ((ParameterizedType) genericType).getActualTypeArguments();
                if(actualTypes.length > 0){
                    for(Type actualType : actualTypes){
                        //     Class
                        Class<?> actualClass = (Class<?>) actualType;
                        System.out.println(actualClass);
                    }
                }
            }
        }
        
        System.out.println();
        System.out.println();
    }
    
    class User{
        private int age;
        private String username;
        private List<User> friends;
        private List<String> friendUsername;
        private Map<String, User> friendNameMap;
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public List<User> getFriends() {
            return friends;
        }
        public void setFriends(List<User> friends) {
            this.friends = friends;
        }
        public List<String> getFriendUsername() {
            return friendUsername;
        }
        public void setFriendUsername(List<String> friendUsername) {
            this.friendUsername = friendUsername;
        }
        public Map<String, User> getFriendNameMap() {
            return friendNameMap;
        }
        public void setFriendNameMap(Map<String, User> friendNameMap) {
            this.friendNameMap = friendNameMap;
        }
        
    }
    
}

  
 
import java.util.List;

public class Class1 {

	private List<String> list;
	private String name1;
	private void add(){
		System.out.println("add---");
	}
	
}

 
 
 
package com.tch.test.concurrent;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ReturnTest {
	private int i;
	public static void main(String[] args) throws Exception{
		m1("name1", Class1.class);
	}
	/**
	 *  Created on: 			2013-11-27 
	 * <p>Discription:			      class           </p>
	 * @param fieldName 	   
	 * @param clazz 			  Class  
	 * @return 				void
	 */
	public static <T> void m1(String fieldName,Class<T> clazz){
		try {
			Field field = clazz.getDeclaredField(fieldName);
			Type type = field.getGenericType(); 
			if (type instanceof ParameterizedType) {     
			    ParameterizedType paramType = (ParameterizedType) type;     
			    Type[] actualTypes = paramType.getActualTypeArguments();     
			    for (Type aType : actualTypes) {         
			        if (aType instanceof Class<?>) {         
			            Class<?> clz = (Class<?>) aType;             
			            System.out.println(clz.getName()); 
			        }     
			    } 
			} 
		}catch (Exception e) {
			e.printStackTrace();
		} 
	}
		
}

 
 
 
プライベートメソッドへのアクセス:
 
	public static void callHiddenMethod(Object a, String methodName) throws Exception {
	    Method g = a.getClass().getDeclaredMethod(methodName);
	    g.setAccessible(true);
	    g.invoke(a);
	}

 
 ターゲットClassオブジェクトの実際の親汎用タイプを取得するには、次の手順に従います.
public class Father<T> {

}

 
public class Child extends Father<String>{

}

 
import java.lang.reflect.ParameterizedType;


public class GenericUtils {

	/**
	 *  Created on: 			2013-11-27 
	 * <p>Discription:			    Class           </p>
	 * @param clazz			  Class  
	 * @return 				Class<T>
	 */
	@SuppressWarnings("unchecked")
	public static <T> Class<T> getGenericType(Class<T> clazz){
		return (Class<T>)((ParameterizedType)clazz.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
}

 テスト方法:
	public static void main(String[] args) throws Exception {
		System.out.println(GenericUtils.getGenericType(Child.class));
	}

 
 
クイックソート/バブルソート:
 
package com.tch.test;

public class QuickSort {
	public void quickSort(int[] arr, int from, int to) {
		if(from >= to){
			return;
		}
		int left = from;
		int right = to;
		int tmp = arr[from];
		while(left < right){
			while(right > left){
				if(arr[right] < tmp){
					arr[left] = arr[right];
					break;
				}
				right --;
			}
			while(left < right){
				if(arr[left] > tmp){
					arr[right] = arr[left];
					break;
				}
				left++;
			}
		}
		arr[left] = tmp;
		quickSort(arr, from, left-1);
		quickSort(arr, right+1, to);
	}

	public void maopao(int[] arr){
		int length = arr.length;
		int tmp = 0;
		for(int i=0;i<length;i++){
			for(int j=(i+1);j<length;j++){
				if(arr[i] > arr[j]){
					tmp = arr[i];
					arr[i] = arr[j];
					arr[j] = tmp;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		int[] arr = new int[] { 1,4,8,2,5,9,7,6,3,10 ,3,5,8,0,1,6 };
		QuickSort sort = new QuickSort();
		//sort.quickSort(strVoid, 0, arr.length - 1);
		sort.maopao(arr);
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}
	}
}

 
 
 
ローを読み込みます.
	/**
	 *  Created on 2013-5-22 
	 * <p>Discription:      </p>
	 * @param in    
	 * @return String         
	 */
	public static String readLine(InputStream in){
		String result = null;
		try {
			byte[] b = new byte[1];
			int n = -1;
			while((n = in.read()) != -1){
				if(n == '\r' || n == '
'){ break; }else{ b[b.length-1] = (byte)n; b = Arrays.copyOf(b, b.length+1); } } if(b.length <= 1){ return null; } b = Arrays.copyOf(b, b.length-1); return new String(b,"utf-8"); } catch (IOException e) { e.printStackTrace(); } return result; }

 
 
servletはpdfをダウンロードします:
package com.tch.excel;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

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


public class ExportExcel extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("application/pdf");
		File file = new File("E:\\  .pdf");
		response.addHeader("Content-Disposition", "attachment;"+new String(("filename=  Excel.pdf").getBytes("GBK"), "ISO-8859-1")); 
		response.setContentLength((int) file.length());
		PrintWriter out = response.getWriter();
		FileReader in = new FileReader(file);
		char[] b = new char[10240];
		int n = -1;
		while((n=in.read(b)) != -1){
			out.write(b, 0, n);
		}
		out.flush();
		out.close();
	}

}

 
 
 
 EXcel::(contentTypeとファイル接尾辞を変更するだけ)
package com.tch.excel;

import java.io.IOException;
import java.io.PrintWriter;

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

@SuppressWarnings("serial")
public class ExportExcel extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("application/x-xls;charset=utf-8");
		response.addHeader("Content-Disposition", "attachment;"+new String(("filename=  Excel.xls").getBytes("GBK"), "ISO-8859-1")); 
		PrintWriter out = response.getWriter();
		out.print("     ");
		out.flush();
		out.close();
	}

}

 
 
 word:(contentTypeとファイル接尾辞を変更するだけ)をダウンロードします.
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("application/msword;charset=utf-8");
		response.addHeader("Content-Disposition", "attachment;"+new String(("filename=  Excel.doc").getBytes("GBK"), "ISO-8859-1")); 
		PrintWriter out = response.getWriter();
		out.print("     ");
		out.flush();
		out.close();
	}

 
 
 エクスポートexcel:
	static void export() throws Exception{
		HSSFWorkbook wb = new HSSFWorkbook();
	    Sheet sheet = wb.createSheet("007");
		HSSFCellStyle style = wb.createCellStyle();
		//    (    setFillBackgroundColor)
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		//        
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		//        
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		//        
		style.setRightBorderColor(HSSFColor.GREY_25_PERCENT.index);
		style.setBottomBorderColor(HSSFColor.GREY_25_PERCENT.index);
		style.setLeftBorderColor(HSSFColor.GREY_25_PERCENT.index);
		style.setTopBorderColor(HSSFColor.GREY_25_PERCENT.index);
		//  、      
		style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
	    Row row = sheet.createRow((short) 1);

	    Cell cell = row.createCell((short) 1);
	    cell.setCellValue("X");
	    cell.setCellStyle(style);

	    cell = row.createCell((short) 2);
	    cell.setCellValue("X");
	    cell.setCellStyle(style);

	    FileOutputStream fileOut = new FileOutputStream("f:workbook.xls");
	    wb.write(fileOut);
	    fileOut.close();
	}

 
 
認証コードを生成します(servletを例にします):
 
package com.tch.excel;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthImage extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static char[] codeArr = new char[] {'a','b','c','d','e','f','g','h','i',
												   'j','k','l','m','n','o','p','q','r',
												   's','t','u','v','w','x','y','z','A',
												   'B','C','D','E','F','G','H','I','J',
												   'K','L','M','N','O','P','Q','R','S',
												   'T','U','V','W','X','Y','Z','0','1',
												   '2','3','4','5','6','7','8','9'};
	private Random random = new Random();
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int length = codeArr.length;
		int width = 200;
		int height = 100;
		//       
		String code = "";
		//                
		String validateCode = "";
		//  BufferedImage  ,            (        )
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//  BufferedImage Graphics  ,Graphics       ,           
		Graphics graphics = bufferedImage.getGraphics();
		//   BufferedImage        
		graphics.setColor(Color.white);
		graphics.fillRect(0, 0, width-1, height-1);
		// BufferedImage       
		graphics.setColor(Color.black);
		graphics.drawRect(0, 0, width-1, height-1);
		//           
		graphics.setFont(new Font("Comic Sans MS",Font.PLAIN,70));
		for(int i=0;i<4;i++){
			//      
			code=""+codeArr[random.nextInt(length)];
			//      
			graphics.setColor(getRandColor());
			//     BufferedImage   (Graphics        BufferedImage    )
			graphics.drawString(code, 5+i*50, 70);
			//           
			validateCode += code;
		}
		System.out.println("validateCode : "+validateCode);
		//         
		graphics.dispose();
		//        response         
		ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
	}
	//      
	private Color getRandColor() {
		Random random = new Random();
		Color color[] = new Color[10];
		color[0] = new Color(32, 158, 25);
		color[1] = new Color(218, 42, 19);
		color[2] = new Color(31, 75, 208);
		return new Color(random.nextInt(220), random.nextInt(220), random.nextInt(220));
	}

}

 次に、Web.xmlでservletを構成します.ページは次のとおりです(xxxはプロジェクト名、servlet/authImageはservletのマッピングパス).
<html>
<head>
<title>     PDF  </title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<script type="text/javascript" charset="utf-8">
			function refreshCode(obj){
				obj.src = 'http://localhost:8080/xxx/servlet/authImage?d='+(new Date().getTime());
			}
		</script>
	</head>
	<body id="dt_example">
		<a href="###"><img src="http://localhost:8080/xxx/servlet/authImage" width="60" height="25" onclick="refreshCode(this);"></a>
	</body>
</html>

 
 
 タスクスケジュール:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class ScheduledTask {
	private static SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        UncaughtExceptionHandler exceptionHandler = null;
	private void task1() {
                exceptionHandler = new UncaughtExceptionHandler(){
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				System.out.println("thread: "+t+" , throwable : "+e);
			}
		};
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(2, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
                                thread.setUncaughtExceptionHandler(exceptionHandler);//    
				return thread;
			}
		});
		//                    (   6 s),            ,              ,             
		executor.scheduleAtFixedRate(new Task("AtFixedRate"), 0, 6, TimeUnit.SECONDS);
		//                       (   6 s),             
		executor.scheduleWithFixedDelay(new Task("WithFixedDelay"), 0, 6, TimeUnit.SECONDS);
	}
	public class Task implements Runnable {
		private String name;
		public Task(String name){
			this.name = name;
		}
		public void run(){
			System.out.println("   : "+name+"   "+format.format(new Date()));
			try {
				TimeUnit.SECONDS.sleep(3);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("   : "+name+"  "+format.format(new Date()));
		}
	}
	public static void main(String[] args) {
		new ScheduledTask().task1();
	}

}

 
 
 2つの方法で消費者を生産しています.
一:比較的低級な方法を使用する:
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Test2 {
    public static void main(String[] args) throws InterruptedException {
    	Test2 t = new Test2();
    	Queue<Integer> container = new LinkedList<Integer>();
		ExecutorService e = Executors.newFixedThreadPool(3);
		e.execute(t.new Producer(container));
		e.execute(t.new Consumer(container));
		e.shutdown();
    }
    
    class Producer implements Runnable{
    	Queue<Integer> container;
		public Producer(Queue<Integer> container){
			this.container = container;
		}
		int i=0;
		Integer get(){
			i++;
			return i;
		}
		@Override
		public void run() {
			try {
				while(true){
					synchronized(container){
						while(container.size()>3){
							container.wait();
						}
						Integer j = get();
						container.add(j);
						System.out.println("   :"+j);
						container.notifyAll();
						Thread.sleep(500);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	} 
	class Consumer implements Runnable{
		Queue<Integer> container;
		public Consumer(Queue<Integer> container){
			this.container = container;
		}
		@Override
		public void run() {
			try {
				while(true){
					synchronized(container){
						while(container.isEmpty()){
							container.wait();
						}
						Integer butter =container.poll();
						System.err.println("   : "+butter);
						container.notifyAll();
						Thread.sleep(500);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

二:高級点を使って、手間を省く方法:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;


public class Test {
	
	public static void main(String[] args) {
		Test t = new Test();
		LinkedBlockingQueue<Integer> container = new LinkedBlockingQueue<Integer>();
		ExecutorService e = Executors.newFixedThreadPool(3);
		e.execute(t.new Producer(container));
		e.execute(t.new Consumer(container));
		e.shutdown();
	}
	class Producer implements Runnable{
		LinkedBlockingQueue<Integer> container;
		public Producer(LinkedBlockingQueue<Integer> container){
			this.container = container;
		}
		int i=0;
		Integer get(){
			i++;
			return i;
		}
		@Override
		public void run() {
			try {
				while(true){
					Integer j = get();
					System.out.println("   :"+j);
					container.put(j);//LinkedBlockingQueue                (   )
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	} 
	class Consumer implements Runnable{
		LinkedBlockingQueue<Integer> container;
		public Consumer(LinkedBlockingQueue<Integer> container){
			this.container = container;
		}
		@Override
		public void run() {
			try {
				while(true){
					Integer butter =container.take();//LinkedBlockingQueue                (   )
					System.err.println("   : "+butter);
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

  
 
 標準jdbc接続手順(バッチと例外ロールバックを使用):
void jdbc() throws Exception{
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");//        
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");//    
			statement = conn.prepareStatement("insert into coures(id,name,age) values(?,?,?)");//  PreparedStatement
			conn.setSavepoint();//     
			conn.setAutoCommit(false);//        
			for(int i=0;i<100;i++){
				statement.setInt(1, i);//    1   
				statement.setString(2, "tch");
				statement.setInt(3, 23);
				statement.addBatch();//      
			}
			statement.executeBatch();//     
			conn.commit();//    ,    
		} catch (Exception e) {
			if(conn != null){
				conn.rollback();//     ,      
			}
			e.printStackTrace();
		}finally{//    
			if(statement != null){
				statement.close();
			}
			if(conn != null){
				conn.close();
			}
		}
	}

 
 
最も簡単なデッドロック:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
	Object o1 = new Object(),o2 = new Object(),o = new Object();
	public static void main(String[] args) throws Exception {
		final Test t = new Test();
		ExecutorService e = Executors.newFixedThreadPool(2);
		e.execute(new Runnable() {
			@Override
			public void run() {
				try {
					t.syn1();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		e.execute(new Runnable() {
			@Override
			public void run() {
				try {
					t.syn2();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		e.shutdown();
	}
	void syn1() throws Exception{
		synchronized(o1){
			System.out.println("syn1     o1    ");
			Thread.sleep(50);//  CPU, syn2     o2  
			synchronized(o2){
				System.out.println("syn1     o2    ");
			}
		}
	}
	void syn2() throws Exception{
		synchronized(o2){
			System.out.println("syn2     o2    ");
			Thread.sleep(50);//  CPU, syn1     o1  
			synchronized(o1){
				System.out.println("syn2     o1    ");
			}
		}
	}
}

 
 
log 4 j構成:
log4j.properties
log4j.rootLogger=debug,stdout,DAILY_ROLLING_FILE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

########################
# DailyRolling File
########################
log4j.appender.DAILY_ROLLING_FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DAILY_ROLLING_FILE.Append=true
log4j.appender.DAILY_ROLLING_FILE.Threshold=debug
log4j.appender.DAILY_ROLLING_FILE.Encoding=UTF-8

#                 
log4j.appender.DAILY_ROLLING_FILE.File=${logDir}/log.txt
log4j.appender.DAILY_ROLLING_FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.DAILY_ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.DAILY_ROLLING_FILE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} [%c] %m%n

###################
# Console Appender
###################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=debug
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p (%c:%L) - %m%n

###################
#          
###################
#  struts2    
log4j.logger.com.opensymphony.xwork2=info
log4j.logger.org.apache.struts2=info
#          
log4j.logger.com.test.LogTest=info

 
 
 
getResourceAsStream、getResourceの使い方:
 
public class ResourceTest {

	public static void main(String[] args) {
		//Class.getResource("path")
		//path  /  ,          
		System.out.println(ResourceTest.class.getResource("").getPath());
		//path /  ,  classpath  
		System.out.println(ResourceTest.class.getResource("/").getPath());
		//ClassLoader.getResource("path")
		//path    /  ,  classpath  
		System.out.println(ResourceTest.class.getClassLoader().getResource("").getPath());
		//         classpath  
		System.out.println(ResourceTest.class.getProtectionDomain().getCodeSource().getLocation().getPath());
	}

}

 
 
 
注釈の使い方と処理(カスタム注釈、注釈の使用、注釈の処理)
 
Web.xmlのロード順序:
 
context-param -> listener -> filter -> servlet
 
Web.xmlでのlistenerのロード順序は、このlistenerのweb.xmlでの構成順序によって決定され、filterの順序はweb.xmlでのfilter-mapping順序によって決定され、servletの順序はweb.xmlでのservlet-mapping順序によって決定される.
 
	<listener>
		<listener-class>com.tch.Listener2</listener-class>
	</listener>
	<listener>
		<listener-class>com.tch.Listener1</listener-class>
	</listener>
  
 
まず2,2が3 s待ちになった後に1,1が3 s待ちになったのは,完全に線形に実行されたことがわかる.
 
 
Listerner1:
 
package com.tch;

import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class Listener1 implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("1 destroy");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("1 init");
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("1 sleep complete");
	}

}

Listener2: 
package com.tch;

import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class Listener2 implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("2 destroy");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("2 init");
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("2 sleep complete");
	}

}

 
 
Spring aop(カスタム断面aspect、aspectjweaver.jar、aspectjrt.jar、cglib-nodep-2.1_3.jar、インタフェースを実装したクラスの最初の2つのエージェント、後者はインタフェースを実装していないクラスのエージェント)が必要です.
    インタフェースの定義:
package com.tch.aspect;  
  
public interface PersonService {  
    public int save(String name) throws Exception;  
    public void update(String name, Integer id);  
    public String getPersonName(Integer id);  
}

   実装クラス:
package com.tch.aspect;

import org.springframework.stereotype.Component;

@Component("personService")
public class PersonServiceBean implements PersonService{  
  
    public String getPersonName(Integer id) {  
        System.out.println("  getPersonName()  ");  
        return "xxx";  
    }  
  
    public int save(String name) {  
    //throw new RuntimeException("    ");  
        //int i = 10/0;  
        System.out.println("  save()  ");  
             return 0;  
    }  
  
    public void update(String name, Integer id) {  
        System.out.println("  update()  ");  
    }  
}

   カスタム断面:
 

package com.tch.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * * */ @Aspect // @Component("myInterceptor") public class MyInterceptor { @Pointcut("execution (* com.tch.aspect.PersonServiceBean.*(..))") private void anyMethod() {}// @Before("anyMethod() && args(name)")// , , String , public void doAccessCheck(String name) { System.out.println(" :"+ name); } @AfterReturning(pointcut="anyMethod()",returning="result") // , int public void doAfterReturning(int result) { System.out.println(" :"+ result); } @AfterThrowing(pointcut="anyMethod()",throwing="e") // public void doAfterThrowing(Exception e) { System.out.println(" :"+ e); } @After("anyMethod()") // public void doAfter() { System.out.println(" "); } @Around("anyMethod()") // public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { //if(){// System.out.println(" "); Object result = pjp.proceed();// , , System.out.println(" "); //} return result; } }

 beans.xml:
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:context="http://www.springframework.org/schema/context"   
       xmlns:aop="http://www.springframework.org/schema/aop"        
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">  
       <context:component-scan base-package="com.tch.aspect"></context:component-scan>
       <aop:aspectj-autoproxy/>   
</beans> 

 テストクラス:
 
 
package com.tch.aspect;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringAOPTest {  
  
    public static void main(String[] args) throws Exception {  
        ApplicationContext cxt = new ClassPathXmlApplicationContext("com/tch/aspect/beans.xml");  
        PersonService personService = (PersonService)cxt.getBean("personService");  
        //PersonServiceBean personService = (PersonServiceBean)cxt.getBean("personService");  
        //PersonService personService = new PersonServiceBean();  
        personService.save("xx");  
        //personService.getPersonName(90);  
    }
}

 
 
 CountDownLatchの使い方:
 
package com.tch.test.concurrent.test;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
	/**     */
	private int num = 3;
	private Random random = new Random();
	/**          */
	private CountDownLatch begin = new CountDownLatch(1);
	/**            */
	private CountDownLatch end = new CountDownLatch(num);
	private ExecutorService executor = Executors.newFixedThreadPool(5);
	
	public static void main(String[] args) {
		new CountDownLatchTest().test();
	}

	private void test() {
		try {
			doTask();
			System.out.println( "   ");
			//         
			begin.countDown();
			//     end     0,            (end.countDown())
			end.await();
			System.out.println("   "+System.currentTimeMillis());
			executor.shutdown();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void doTask(){
		for(int i=0;i<num;i++){
			executor.execute(new Task(i));
		}
	}
	
	class Task implements Runnable{
		private int id;
		public Task(int id){
			this.id = id;
		}
		@Override
		public void run() {
			try {
				//  begin      0,            
				begin.await();
				Thread.sleep(random.nextInt(1500));
				System.out.println("  "+id+"  "+System.currentTimeMillis());
				// end     ,end     
				end.countDown();
				//  end     0,            
				end.await();
				System.out.println("       "+System.currentTimeMillis());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

 
 
 CyclicBarrierの使い方:
 
package com.tch.test.concurrent.test;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {
	private CyclicBarrier barrier;
	/**     */
	private int num = 3;
	private Random random = new Random();
	private ExecutorService executor = Executors.newFixedThreadPool(5);

	public static void main(String[] args) {
		new CyclicBarrierTest().test();
	}

	private void test() {
		barrier = new CyclicBarrier(num, new Runnable() {
			@Override
			public void run() {
				System.out.println("      "+System.currentTimeMillis());
				System.out.println(barrier.getNumberWaiting()+"  "+barrier.getParties());
				//barrier.reset();
				System.out.println("--------------    ------------");
				doTask();
			}
		});
		doTask();
		barrier.reset();
		//executor.shutdown();
	}
	//barrier.reset();
	private void doTask(){
		for(int i=0;i<num;i++){
			executor.execute(new Task(i));
		}
	}
	
	class Task implements Runnable{
		private int id;
		public Task(int id){
			this.id = id;
		}
		@Override
		public void run() {
			try {
				Thread.sleep(random.nextInt(1500));
				System.out.println("  "+id+"  "+System.currentTimeMillis());
				barrier.await();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

 
 
 HttpServeretRequestによるDomainPathの取得: 
 
	/**
	 *    HttpServletRequest  DomainPath
	 */
	public static String getDomainPath(HttpServletRequest request) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + path + "/";
		return basePath;
	}

 
 
無視しやすい知識点:
 
1.マルチステートとは、一般的にメソッドのマルチステートを指します.一般的には、コンパイル中にプロパティへのアクセスが決定されたため、プロパティのマルチステートは含まれません.
 
package test.extend;

public class Father {

	public int field = 1;
	
}
 
package test.extend;

public class Child extends Father{

	public int field = 9;
	
}
 
package test;

import test.extend.Child;
import test.extend.Father;


public class Test {

	public static void main(String[] args) throws Exception {
		Father f = new Child();
		System.out.println(f.field);
		Child f2 = new Child();
		System.out.println(f2.field);
	}
	
}
 
 
 1番目の出力結果は親の値:1、2番目の出力結果は子の値:9です.   
 
 2.プライベートメソッドを上書きすることはできません.また、プライベートメソッドのマルチステートは存在しません.
 
 
package test.extend;

public class Father {

	private void m(){
		System.out.println("father  method  m");
	}
	
	public void p(){
		System.out.println("father method p");
	}

	/**
	 * Create Date:		2014-1-6  9:13:51
	 * @author:			 O、  
	 * @param args
	 */
	public static void main(String[] args) {
		Father f = new Child();
		//         m  ,    m    ,     
		f.m();
		//         p  ,    p     ,     
		f.p();
	}
}

 
package test.extend;

public class Child extends Father{

	public void m(){
		System.out.println("child method m");
	}

	public void p(){
		System.out.println("child method p");
	}
	
}

 出力の結果:
father  method  m
child method p
 
ここで子クラスでのメソッドmは実は新しいメソッドであり,親クラスのmメソッドとは何の関係もない.
 
 3.サブクラスが継承されている場合、構築方法の問題:構築方法がまだ完了していない場合、操作が実行され、オブジェクトが初期化されていない場合、不明な問題が発生します.たとえば、次のようにします.
package test.extend;

public class Father {

	public Father(){
		System.out.println("Father  before draw");
		draw();
	}
	
	public void draw(){
		System.out.println("father  method  draw");
	}
	
}
package test.extend;

public class Child extends Father{

	public int field = 9;
	
	public Child(int r){
		field = r;
		System.out.println("child : field="+field);
	}
	
	public void draw(){
		System.out.println(" child draw : field="+field);
	}
	
}
package test;

import test.extend.Child;


public class Test {

	public static void main(String[] args) throws Exception {
		new Child(10);
	}
	
}

 
この例のフローは、サブクラス構築メソッドを実行する前に、親の構築メソッドを実行する必要があり、親の構築メソッドが実行されるとdrawメソッドが呼び出されます.マルチステートの要因で、サブクラスのdrawメソッドが呼び出されます.この場合、サブクラスのプロパティはまだ初期化されていません.したがって、0で、サブクラス構築メソッドが実行されます.この場合、サブクラスのプロパティは初期化されます.値は10です
 
次に、初期化の基本手順を記録します.
 
1.親静的コードの初期化
2.初期化サブクラス静的コード
3.親非静的コードの初期化
4.親構築メソッドの初期化
5.初期化サブクラス非静的コード
6.初期化子類の構造方法
 
以上の流れにより,判定流れを明確に実行することができる.
 
 
 
ZIP簡単圧縮解凍(簡単に実現し、厳格ではなく、学習としてのみ使用する):
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class ZipCompress {

	/**
	 *           sourceFileDirs   zip  ,       destFileDir
	 * Create Date:		2014-1-6  11:15:36
	 * @author:			 O、  
	 * @param sourceFileDirs           
	 * @param destFileDir               
	 * @throws Exception
	 */
	public static void zipCompress(String[] sourceFileDirs,String destFileDir) throws Exception{
		FileOutputStream f = new FileOutputStream(destFileDir);
		CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
		ZipOutputStream zos = new ZipOutputStream(csum);
		BufferedOutputStream out = new BufferedOutputStream(zos);
		zos.setComment("A test of Java Zipping");
		for (String fileDir : sourceFileDirs) {
			BufferedReader in = new BufferedReader(new FileReader(fileDir));
			zos.putNextEntry(new ZipEntry(fileDir));
			int c;
			while ((c = in.read()) != -1)
				out.write(c);
			in.close();
			out.flush();
		}
		out.close();
	}
	
	/**
	 *          
	 * Create Date:		2014-1-6  11:48:31
	 * @author:			 O、  
	 * @param srcFileDir	        
	 * @param destFolder         
	 * @throws Exception
	 */
	public static void zipDeCompress(String srcFileDir,String destFolder) throws Exception{
		FileInputStream fi = new FileInputStream(srcFileDir);
		CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
		ZipInputStream in2 = new ZipInputStream(csumi);
		BufferedInputStream bis = new BufferedInputStream(in2);
		ZipEntry ze;
		byte[] b = new byte[20480];
		int n = -1;
		File destFile = null;
		BufferedOutputStream out = null;
		while ((ze = in2.getNextEntry()) != null) {
			destFile = new File(generateFullFileName(destFolder,getSimpleName(ze.getName())));
			if(! destFile.getParentFile().exists()){
				destFile.getParentFile().mkdirs();
			}
			if(! destFile.exists()){
				destFile.createNewFile();
			}
			out = new BufferedOutputStream(new FileOutputStream(destFile), 20480);
			while ((n = bis.read(b)) != -1){
				out.write(b, 0, n);
				out.flush();
			}
			out.flush();
			out.close();
		}
		bis.close();
	}
	
	/**
	 *          
	 * Create Date:		2014-1-6  11:48:31
	 * @author:			 O、  
	 * @param srcFileDir	        
	 * @param destFolder         
	 * @throws Exception
	 */
	public static void zipDeCompress2(String srcFileDir,String destFolder) throws Exception{
		FileInputStream fi = new FileInputStream(srcFileDir);
		CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
		ZipInputStream in2 = new ZipInputStream(csumi);
		BufferedInputStream bis = new BufferedInputStream(in2);
		ZipFile zf = new ZipFile(srcFileDir);
		Enumeration<?> e = zf.entries();
		byte[] b = new byte[20480];
		int n = -1;
		File destFile = null;
		BufferedOutputStream out = null;
		while (e.hasMoreElements()) {
			ZipEntry ze = (ZipEntry) e.nextElement();
			destFile = new File(generateFullFileName(destFolder,getSimpleName(ze.getName())));
			if(! destFile.getParentFile().exists()){
				destFile.getParentFile().mkdirs();
			}
			if(! destFile.exists()){
				destFile.createNewFile();
			}
			out = new BufferedOutputStream(new FileOutputStream(destFile), 20480);
			while ((n = bis.read(b)) != -1){
				out.write(b, 0, n);
				out.flush();
			}
			out.flush();
			out.close();
		}
		zf.close();
		bis.close();
	}
	
	public static String getSimpleName(String name){
		int index = Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\"));
		return name.substring(index+1);
	}
	
	public static String generateFullFileName(String folder,String fileName){
		if(! folder.endsWith("/") && ! folder.endsWith("\\")){
			folder += File.separator;
		}
		System.out.println(folder+fileName);
		return folder+fileName;
	} 
	
	public static void main(String[] args) throws Exception {
		//zipDeCompress("E:\\test.zip", "e:/decompress");
		zipDeCompress2("E:\\test.zip", "e:/decompress");
	}
	
}

 
 
JAVA-JSON処理:
 
public static String pack(Object result,JsonResultType type){
		Map<Object,Object> rt=new HashMap<Object,Object>();
		rt.put("result", result);
		JSONArray jsonArray = JSONArray.fromObject(rt);
		String jsonResult = jsonArray.toString();
		return jsonResult;
	}

 
 JAva生成GUID:
 
/**
	 *   UUID
	 * <p>Created on 2014-2-17 </p>
	 * @return
	 */
	public static String getUUID(){ 
        return UUID.randomUUID().toString(); 
    } 
	/**
	 *   UUID    “-” 
	 * <p>Created on 2014-2-17 </p>
	 * @return
	 */
	public static String getUUID2(){ 
        String s = UUID.randomUUID().toString(); 
        //  “-”   
        return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); 
    } 

 
 
 HashMapにおけるequals法とhashcode法の役割をまとめた.
 
まずputのプロセスについて,まずhashcodeに基づいてhashテーブルにおけるbucket(固定サイズの配列,個人推定)を算出し,そのbucketの容量が満たされているかどうかを確認し,不満であればそのデータを追加し,満たされていればいくつかのパラメータに基づいてbucketの容量を拡大する.
 
次にgetのプロセスで、まずkeyで計算したhashコードに基づいて対応するbucketを見つけて、それからこのbucketの中にどれだけのデータがあるかを見て、1つだけあれば直接取り出して、1つ以上あればequals遍歴によって結果を取り出します
 
キーとして最適なのはStringとIntegerで、もちろん他のカスタムオブジェクトでも可能ですが、カスタムオブジェクトはequalsとhashcodeメソッドを書き換えると、要素がhashテーブルに分散し、読み書き効率が向上します.
 
 
次にvolatileについてお話しします  :
マルチスレッド同時プログラミングではsynchronizedとVolatileが重要な役割を果たしています.Volatileは軽量級のsynchronizedで、マルチプロセッサ開発で共有変数の「可視性」を保証しています.可視性とは、あるスレッドが共有変数を変更すると、別のスレッドがこの変更の値を読むことができることを意味します.
 
 
そしてConcurrentHashMapについて
 
および  ConcurrentHashMap(2)を深く分析する
getと同時に別のスレッドがput/removeの操作を実行している場合,どのような状況であるかを解析した.
 
ConcurrentHashMapはHashTableよりも効率が高いのは、ConcurrentHashMapがデータをセグメント化した後、異なるロックで異なるセグメントデータをロックし、各ロックはそのセグメントデータに対応する読み書き操作のみを担当し、そのうちのセグメントデータを読み書きする場合、他のデータは読み書きでき、影響しないからです.一方、HashTableは、synchronizedキーワードをロックするすべての方法です.
 
get操作の効率的な点は、getプロセス全体にロックをかける必要がなく、読み取った値が空でない限りロックをかけて再読み込みすることができないことです.HashTableコンテナのget方法にロックをかける必要があることを知っています.では、ConcurrentHashMapのget操作はどのようにロックをかけないことができますか.なぜなら、getメソッドでは、現在のSegementサイズを統計するcountフィールドや値を格納するHashEntryのvalueなど、使用する共有変数をvolatileとして定義しているからです.volatileとして定義された変数は、スレッド間で可視性を保つことができ、マルチスレッドで同時に読むことができ、期限切れの値が読めないことを保証するが、単一スレッドで書くことしかできない(マルチスレッドで書くことができる場合があり、書き込む値は元の値に依存しない)ため、get操作では共有変数countやvalueを読む必要がないだけなので、ロックをかけなくてもよい.期限切れの値が読めないのは、javaメモリモデルのhappen beforeの原則に基づいて、volatileフィールドへの書き込み操作が読み取り操作より先に行われ、2つのスレッドがvolatile変数を同時に修正して取得してもget操作は最新の値を得ることができ、ロックをvolatileで置き換える古典的なアプリケーションシーンです.
 
 
 
LinkedListをカスタマイズし、そのreverseメソッドを自分で実装します.
 
 
package com.tch.test.test;

public class T {

	public static void main(String[] args) {
		MyLinkedList list = new MyLinkedList();
		list.add(new Node("1"));
		list.add(new Node("2"));
		list.add(new Node("3"));
		list.add(new Node("4"));
		list.add(new Node("5"));
		list.add(new Node("6"));
		System.out.println("   --------");
		Node n = list.getTop();
		System.out.println(n.getObj());
		while(n.getNextNode() != null){
			System.out.println(n.getNextNode().getObj());
			n = n.getNextNode();
		}
		reverse(list);
		System.out.println("   --------");
		n = list.getTop();
		System.out.println(n.getObj());
		while(n.getNextNode() != null){
			System.out.println(n.getNextNode().getObj());
			n = n.getNextNode();
		}
	}
	
	/**
	 *     list   
	 * <p>Created on 2014-3-19 </p>
	 * @param list        list
	 */ 
	public static void reverse(MyLinkedList list){
		//            
		resursiveReverse(list.getTop(),list.getTop().getNextNode(),list);
	}
	/**
	 *       
	 * <p>Created on 2014-3-19 </p>
	 * @param pre      
	 * @param next      
	 * @param list        list
	 */
	public static void resursiveReverse(Node pre,Node next,MyLinkedList list){
		//  nextNode null,          
		if(next.getNextNode() == null){
			next.setNextNode(pre);
			list.getTop().setNextNode(null);
			list.setTop(next);
		}else{
			//       ,  
			resursiveReverse(next,next.getNextNode(),list);
			//                (         nextNode         )
			next.setNextNode(pre);
		}
	}
	
}
/**
 * Created on 2014-3-19
 * <p>Description:      </p>
 */
class MyLinkedList{
	/**
	 *   list       
	 */
	private Node top;
	public void add(Node n){
		n.setNextNode(top);
		top = n;
	}
	public Node getTop() {
		return top;
	}
	public void setTop(Node top) {
		this.top = top;
	}
	
}
class Node{
	/**
	 *        
	 */
	private Object obj;
	/**
	 *           
	 */
	private Node nextNode;
	
	public Node(Object obj) {
		super();
		this.obj = obj;
	}
	public Object getObj() {
		return obj;
	}
	public void setObj(Object obj) {
		this.obj = obj;
	}
	public Node getNextNode() {
		return nextNode;
	}
	public void setNextNode(Node nextNode) {
		this.nextNode = nextNode;
	}
	
}

 
 DbVisualizer
 
データベース関係を表示するツール
 
2つの期間が重複しているかどうかを確認します.
 
 
public static boolean overlapWithEachOther(Date startTime, Date stopTime, Date theOtherStartTime, Date theOtherStopTime) {
        if(startTime == null && stopTime == null){
            throw new IllegalArgumentException("startTime&stopTime can not be null at the same time");
        }
        if(theOtherStartTime == null && theOtherStopTime == null){
            throw new IllegalArgumentException("startTime&stopTime can not be null at the same time");
        }
        if(startTime == null || stopTime == null){
            if(startTime == null){ // means startTime(null) and stopTime(not-null)
                if(! (theOtherStartTime != null && ! theOtherStartTime.before(stopTime))){
                    // has overlap
                    return true;
                }
            }else{ // means startTime(not-null) and stopTime(null)
                if(! (theOtherStopTime != null && ! theOtherStopTime.after(startTime))){
                    // has overlap
                    return true;
                }
            }
        }
        if(theOtherStartTime == null || theOtherStopTime == null){
            if(theOtherStartTime == null){ // means theOtherStartTime(null) and theOtherStopTime(not-null)
                if(! (startTime != null && ! startTime.before(theOtherStopTime))){
                    // has overlap
                    return true;
                }
            }else{ // means theOtherStartTime(not-null) and theOtherStopTime(null)
                if(! (stopTime != null && ! stopTime.after(theOtherStartTime))){
                    // has overlap
                    return true;
                }
            }
        }
        if(startTime != null && stopTime != null && theOtherStartTime != null && theOtherStopTime != null){
            if(theOtherStartTime.before(startTime) && theOtherStopTime.after(startTime)){
                return true;
            }
            if(! theOtherStartTime.before(startTime) && theOtherStartTime.before(stopTime)){
                return true;
            }
        }
        return false;
    }

 
JAVA中float double加算減算操作で発生した精度の問題:
 
 
        double d = (2.8 - 2.0);
        System.out.println(d);
        
        float f = (2.8f - 2.0f);
        System.out.println(f);

 
出力の結果は次のとおりです.
 
 
0.7999999999999998
0.79999995

 
 
この問題を解決するには、(BigDecimal Stringの構造方法を使用することに注意し、この方法は精度を保証することができる):
 
BigDecimal(String.valueOf(value));
 
の双曲線コサインを返します.
例:
 
 
        BigDecimal b2 = new BigDecimal(String.valueOf(a)).subtract(new BigDecimal(String.valueOf(b)));
        System.out.println(b2);

 
結果は次のとおりです.
 
 
2.8

 
 
instanceof/isInstance/isAssignableFromの使い方
 
        String s = "abc";
        // instanceof: object is an instance of the class
        System.out.println(s instanceof String);
        System.out.println(s instanceof Object);
        // Class.isInstance
        System.out.println(String.class.isInstance(s));
        System.out.println(Object.class.isInstance(s));
        // Class.isAssignableFrom
        System.out.println(Object.class.isAssignableFrom(s.getClass()));
        System.out.println(String.class.isAssignableFrom(s.getClass()));

 
Javaのヒープとスタック:
public static void main(String[] args) throws Exception {
        m(1);
    }
    
    
    
    private static void m(int i){
        m(i);
    }

 
このように無限ループすると、StackOverflowError.(基本タイプのデータ値はスタックに格納され、スタックスペースが不足するとStackOverflowErrorが現れる)
 
しかし、次のようにします.
public static void main(String[] args) throws Exception {
        m(new byte[1024000]);
    }
    
    private static void m(byte[] i){
        m(new byte[1024000]);
    }

 
これでOutOfMemoryErrorが現れます.(new byte[xxx]はスタックに格納されているため、占有スペースが不足するとOutOfMemoryErrorが現れる)
 
 
JAva正規表現は、String testStr=「我们一致通过等高公里链接。       ";
ハイパーリンクを一致させるには、次のようにします.
 
 
 
 
最初はを用いてマッチングしたが、結果は以下のようになった.
       
 
つまり、実は後ろのが文字列の最後のにマッチしていて、悪漢のような感じがしますが、私が望んでいるのは怠け者の結果で、最初のマッチングを手に入れたら、最後のマッチングではなく戻ってきます.
 
長い間やっていたが、最後に少し変えるだけで、いわゆる怠け者のマッチングに達することができることに気づいた.
是的,.*后面会追加吗?それでいいです。参考资料:Java正則における(.*?)vs.*)の違い
 
コード:
 
package com.tch.test;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegExp {

	public static void main(String[] args) throws IOException {
		String testStr = "<a href=\"www.baidu1.com\">  </a>  <a href=\"www.baidu2.com\">  </a>  <a href=\"www.baidu3.com\">  </a>";
		String regex = "<a .*?</a>";
//		String regex = "<a .*?href.*?>.*?</a>";
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(testStr);
		while (matcher.find()) {
			System.out.println(matcher.group(0));
//			int gc = matcher.groupCount();
//			for (int i = 0; i <= gc; i++) {
//				System.out.println("group " + i + " :" + matcher.group(i));
//			}
		}
	}

}