달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
2013. 5. 2. 15:54

enum 사용하기 그거/Java2013. 5. 2. 15:54

enum 잘 안썼는데..  걍 정리해봄.


1. 단순 상수로 사용하기

public enum Gender { MALE, FEMALE };

public static void main(String[] args) {

System.out.println(Gender.MALE);

}


# 출력 #

MALE



2. 값 설정해서 사용하기

public enum Gender {

MALE(1), FEMALE(2);

private int value;

private Gender(int value) {

this.value = value;

}

public int getValue() {

return this.value;

}

}


public static void main(String[] args) {

System.out.println(Gender.MALE);

System.out.println(Gender.MALE.getValue());

}


# 출력 #

MALE

1



3. method override 해서 사용하기

public enum Gender {

MALE(1), FEMALE(2);

private int value;

private Gender(int value) {

this.value = value;

}

public int getValue() {

return this.value;

}

public String toString() {

switch(value) {

case 10 :

return "MAN";

case 20:

return "WOMAN";

default :

return "???";

}

}

}


public static void main(String[] args) {

System.out.println(Gender.MALE);

System.out.println(Gender.MALE.getValue());

System.out.println(Gender.FEMALE);

System.out.println(Gender.FEMALE.getValue());

}


# 출력 #

MAN

10

WOMAN

20



4. switch/case 에 사용하기

public enum Gender {

MALE(1), FEMALE(2);

private int value;

private Gender(int value) {

this.value = value;

}

public int getValue() {

return this.value;

}

public String toString() {

switch(value) {

case 10 :

return "MAN";

case 20:

return "WOMAN";

default :

return "???";

}

}

}


public static void main(String[] args) {

Gender male = Gender.MALE;

switch(male) {

case MALE:

System.out.println("MAN~~~");

break;

case FEMALE:

System.out.println("WOMAN~~~");

break;

default :

System.out.println("UHM.....");

break;

}

}


# 출력 #

MAN~~~


'그거 > Java' 카테고리의 다른 글

Spring 의 SimpleJdbcCall 이용시 에러.  (0) 2014.05.19
JSP 의 EL 과 JSTL  (0) 2013.08.09
자바 소스 디컴파일 해보기.  (0) 2013.04.11
Runtime Data Access  (0) 2012.07.30
NoClassDefFoundError vs ClassNotFoundException  (0) 2011.10.11
:
Posted by 뽀기
2013. 4. 11. 15:05

자바 소스 디컴파일 해보기. 그거/Java2013. 4. 11. 15:05


서버에 있는 class 파일과 PC 에 있는 class 파일의 크기가 달라서

서버의 class 파일과 PC의 class 파일을 decompile 해서 비교하다 보니 아래와 같이 알 수 없는 문장(?)들이 있어서


        break MISSING_BLOCK_LABEL_361;

        Exception exception;

        exception;

        if(bw != null)

            bw.close();

        throw exception;

        if(bw != null)

            bw.close();

그래서, decompile 테스트 해봤다.


BufferedReader br = null;

try {

System.out.println("try >>");

br = new BufferedReader(new InputStreamReader(System.in));

br.readLine();

System.out.println("try <<");

} catch(Exception e) {

System.out.println("catch >>");

e.printStackTrace();

System.out.println("catch <<");

} finally {

System.out.println("finally >>");

if( br != null ) {

try { 

System.out.println("finally try >>");

br.close(); br = null; 

System.out.println("finally try <<");

} catch(Exception ignr) {

System.out.println("finally catch");

}

}

System.out.println("finally <<");

}

System.out.println("000");

ArrayList list = new ArrayList();

for(int i = 0; i < list.size();) {

Object o = list.get(0);

break;

}

System.out.println("111");


int j = 0;

if( j < list.size() ) {

Object o = list.get(0);

}

System.out.println("222");


for(int i = 0; i < list.size(); i++) {

Object o = list.get(i);

}

System.out.println("333");


위의 자바 소스를 컴파일 한 후 class 파일을 디컴파일 해보면 아래와 같다.


        BufferedReader bufferedreader = null;

        System.out.println("try >>");

        bufferedreader = new BufferedReader(new InputStreamReader(System.in));

        bufferedreader.readLine();

        System.out.println("try <<");

        System.out.println("finally >>");

        if(bufferedreader != null)

            try

            {

                System.out.println("finally try >>");

                bufferedreader.close();

                bufferedreader = null;

                System.out.println("finally try <<");

            }

            catch(Exception exception)

            {

                System.out.println("finally catch");

            }

        System.out.println("finally <<");

        break MISSING_BLOCK_LABEL_234;

        Exception exception1;

        exception1;

        System.out.println("catch >>");

        exception1.printStackTrace();

        System.out.println("catch <<");

        System.out.println("finally >>");

        if(bufferedreader != null)

            try

            {

                System.out.println("finally try >>");

                bufferedreader.close();

                bufferedreader = null;

                System.out.println("finally try <<");

            }

            catch(Exception exception2)

            {

                System.out.println("finally catch");

            }

        System.out.println("finally <<");

        break MISSING_BLOCK_LABEL_234;

        Exception exception3;

        exception3;

        System.out.println("finally >>");

        if(bufferedreader != null)

            try

            {

                System.out.println("finally try >>");

                bufferedreader.close();

                bufferedreader = null;

                System.out.println("finally try <<");

            }

            catch(Exception exception4)

            {

                System.out.println("finally catch");

            }

        System.out.println("finally <<");

        throw exception3;

        System.out.println("000");

        ArrayList arraylist = new ArrayList();

        int i = 0;

        Object obj;

        if(i < arraylist.size())

            obj = arraylist.get(0);

        System.out.println("111");

        i = 0;

        if(i < arraylist.size())

            obj = arraylist.get(0);

        System.out.println("222");

        for(int j = 0; j < arraylist.size(); j++)

        {

            Object obj1 = arraylist.get(j);

        }


        System.out.println("333");

        return;


디컴파일한 소스를 보면 finally 가 3번이나 나온다.

그리고, 1번만 실행되는 for문(2번 이상 실행되지 않는 for문)은

알아서 for 문의 조건만 포함한 if문으로 변경된다.


아. 젤 위에 있는 이상한 문장(?)들은 catch 와 finally 에 있는 코드들인듯 하돠.

뭐 새로울 건 없지만, 소스 분석하다가 재밌어서 올려봄.. ㅡ,.ㅡ;

'그거 > Java' 카테고리의 다른 글

JSP 의 EL 과 JSTL  (0) 2013.08.09
enum 사용하기  (0) 2013.05.02
Runtime Data Access  (0) 2012.07.30
NoClassDefFoundError vs ClassNotFoundException  (0) 2011.10.11
Eclipse 에서 Maven 이용해서 remote repository 에 deploy 하기  (0) 2011.10.05
:
Posted by 뽀기
2012. 7. 30. 10:06

Runtime Data Access 그거/Java2012. 7. 30. 10:06

Java 의 변수 구분


- Class Variables

- Member Variables

- Parameter Variables

- Local Variables


- Class Variable

static 변수. Class 에 속해 있는 변수.

Method Area 의 Class Variable 영역에 할당.

모든 Thread 에 의해 공유.


- Member Variable

instance 변수. instance 에 속해 있는 변수


- Parameter Variable

method 의 매개변수. method 에 속해 있는 변수.

변수의 정보는 Method Area 의 Method Information에 포함.

JVM Stacks 에 할당.


- Local Variable

Parameter Variable 과 동일한 부류. method 내에서 정의되는 변수.

Local Variable 은 Parameter Variable 과 같이 Method Information 에 변수 정보가 위치하고 JVM Stacks 에 할당.


Class VariableArrange {

static int ci = 3 ;    // Class Variable

int mi = 4;            // Member Variable


void method(int pi, String ps) {    // Parameter Variable

int li = 5;                            // Local Variable

}

}



중요!!!

Parameter Variable 과 Local Variable 은 Thread Safe 변수.

사용자가 Method 내에서 선언한 Local Variable 의 값에 대해 다른 Thread 의 접근이 불가능.

JVM Stacks 는 다른 Thread 에 의해 접근이 불가능하기 때문.


- 출처 : Java Performance Fundamental (김한도 지음) -

:
Posted by 뽀기
2011. 10. 11. 16:41

NoClassDefFoundError vs ClassNotFoundException 그거/Java2011. 10. 11. 16:41


NoClassDefFoundError
- 컴파일 시점
에는 존재했으나, 실행 내부적으로 loading 되는 class가 없을 때

예제) 아래와 같은 java 자원들을 컴파일 한 후 B.class 파일을 삭제하고 java C 하면 NoClassDefFoundError 발생

Class A extends B {
}

Class B {


Class C {
    public static void main(String[] args) {
        A a = new A a();
    }


예제)  아래와 같은 java 자원들을 컴파일 한 후 D.class 파일을 삭제하고 java E 하면 NoClassDefFoundError 발생

class D {
}

 Class E {

    public static void main(String[] args) {

        D d = new D();

    }



ClassNotFoundException
해당 class 파일이 없을 때(클래스를 로딩하려는 명시적인 시도가 실패할 경우)

예)  아래와 같은 java 자원들을 컴파일 한 후 C.class 파일을 삭제하고 java C 하면 ClassNotFoundException 발생

Class A extends B {

}


Class B {


Class C {

    public static void main(String[] args) {

        A a = new A a();

    }



정리하면,

ClassNotFoundException
 => ClassLoader가 로딩하려고 하는 class가 존재하지 않을 경우 발생
NoDefFoundClassError
 => 
ClassLoader가 로딩하는 명시적인 class 내부에서 묵시적으로 로딩하고자 하는 class가 존재하지 않을 경우 발생
:
Posted by 뽀기
2011. 9. 30. 10:02

Java에서 Cookie 값 꺼내쓰기 유틸.. 그거/Java2011. 9. 30. 10:02


걍.. 만들어 봄 ㅎㅎ

makeCookie.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>

<%@ page import="java.net.*" %>

<%

Cookie cookie1 = new Cookie("CJW1", URLEncoder.encode("cAT=A&cBT=B&cCT=C&cDT=D", "euc-kr"));

Cookie cookie2 = new Cookie("CJW2", URLEncoder.encode("cAT=A&cBT=B&cCT=C&cDT=D", "euc-kr"));

Cookie cookie3 = new Cookie("CJW3", URLEncoder.encode("cAT=A&cBT=B&cCT=C&cDT=D", "euc-kr"));

Cookie cookie4 = new Cookie("CJW4", URLEncoder.encode("cAT=A&cBT=B&cCT=C&cDT=D", "euc-kr"));

response.addCookie(cookie1);

response.addCookie(cookie2);

response.addCookie(cookie3);

response.addCookie(cookie4);


%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<a href="getCookie.jsp">getCookie</a>

</body>

</html>

 
getCookie.jsp 

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>

<%@ page import="java.net.*" %>

<%!

class CookieBook {

private Cookie[] cookies = null;

private HashMap<String, String> cookiesMap = new HashMap<String, String>();

public CookieBook(Cookie[] cookies) {

this.cookies = cookies;

makeCookiesMap();

}

private void makeCookiesMap() {

for(Cookie cookie : cookies) {

String value = null;

String key = cookie.getName();

try {

value = URLDecoder.decode(cookie.getValue(), "euc-kr");

} catch(Exception e) {

value = cookie.getValue();

}

cookiesMap.put(key, value);

if( value.indexOf("&") > 0 ) {

parseData(key, value);

}

}

}

public String getCookieValue(String key) {

if( cookiesMap.containsKey(key) ) {

return cookiesMap.get(key);

} else {

return null;

}

}

private void parseData(String key, String value) {

System.out.println(value);

String[] datas = value.split("&");

for(String data : datas) {

int idx = data.indexOf("=");

if( idx != -1 ) {

String tmpKey = key + "." + data.substring(0, idx);

String tmpData = data.substring(idx+1);

cookiesMap.put(tmpKey, tmpData);

}

}

}

public HashMap<String, String> getMap() {

return cookiesMap;

}

}

%>

<%

CookieBook cookBook = new CookieBook(request.getCookies());

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<table border=1>

<tr>

<th>KEY</th><th>VALUE</th>

</tr>

<%

Iterator<String> keys = cookBook.getMap().keySet().iterator();


while(keys.hasNext()) {

String key = keys.next();

%>

<tr>

<td><%= key %></td><td><%= cookBook.getCookieValue(key) %></td>

</tr>

<%

}

%>

</table>

</body>

</html>

 
CookieBook 이라는 유틸 클래스 만들어서 사용 ㅎ

 KEY  VALUE
CJW4.cCT   C
CJW4  cAT=A&cBT=B&cCT=C&cDT=D
JSESSIONID  HgjlTGnbyRp75pBBPGCXGN3myQgyL7pYVTFvfGgFvBgTpPYhzzTM!-702582978

요딴식으로 보임.
 
:
Posted by 뽀기
2011. 7. 12. 19:10

String.sprlit() 의 사용.. 그거/Java2011. 7. 12. 19:10


   String str = "SELECT * FROM ( "+

   " SELECT ROWNUM AS RNUM, A.* FROM( SELECT * FROM EX_TABLE WHERE 1=1"+

   "  ) A "+

   ") WHERE RNUM >= 1 AND RNUM < 51";

   

   String[] sss = str.split(" ");

   

   for(String s : sss) {

    System.out.println("#" + s + "#");

   }


위와 같이 한 후 돌려보면
 

#SELECT#

#*#

#FROM#

#(#

##

#SELECT#

#ROWNUM#

#AS#

#RNUM,#

#A.*#

#FROM(#

#SELECT#

#*#

#FROM#

#EX_TABLE#

#WHERE#

#1=1#

##

#)#

#A#

#)#

#WHERE#

#RNUM#

#>=#

#1#

#AND#

#RNUM#

#<#

#51#

 
이런 결과를 얻게된다.

white space 를 기준으로 String을 쪼개고 싶을 때는 아래와 같이 하자!

   String str = "SELECT * FROM ( "+

   " SELECT ROWNUM AS RNUM, A.* FROM( SELECT * FROM EX_TABLE WHERE 1=1"+

   "  ) A "+

   ") WHERE RNUM >= 1 AND RNUM < 51";

   

   String[] sss = str.split("\\s+");

   

   for(String s : sss) {

    System.out.println("#" + s + "#");

   }

 
그러면, 아래와 같이 나온다.

#SELECT#

#*#

#FROM#

#(#

#SELECT#

#ROWNUM#

#AS#

#RNUM,#

#A.*#

#FROM(#

#SELECT#

#*#

#FROM#

#EX_TABLE#

#WHERE#

#1=1#

#)#

#A#

#)#

#WHERE#

#RNUM#

#>=#

#1#

#AND#

#RNUM#

#<#

#51#

 
## 이 놈들이 사라졌다. 

'그거 > Java' 카테고리의 다른 글

Java에서 Cookie 값 꺼내쓰기 유틸..  (0) 2011.09.30
MSSQL의 JDBC 로의 컬럼 타입 매핑  (0) 2011.08.08
String.intern() 메소드  (0) 2011.05.02
Use of String in Java  (0) 2011.05.02
Profiling by using NetBeans.  (0) 2011.04.28
:
Posted by 뽀기
2011. 5. 2. 19:41

String.intern() 메소드 그거/Java2011. 5. 2. 19:41


String.intern( ) returns the String object that is being stored in the internal VM string pool. If two Strings are equal, then their

intern( ) results are identical; for example, if s1.equals(s2) is true, then s1.intern( ) == s2.intern( ) is

also true.

 
String.intern() 메소드는 VM 내부의 String pool 에서의 String 객체를 반환한다.
두 String 객체의 내용이 같다면 intern() 메소도가 반환하는 값도 같다.

즉,
s1.equals(s2) == true 는 s1.intern() == s2.intern()
이다.
 

'그거 > Java' 카테고리의 다른 글

MSSQL의 JDBC 로의 컬럼 타입 매핑  (0) 2011.08.08
String.sprlit() 의 사용..  (0) 2011.07.12
Use of String in Java  (0) 2011.05.02
Profiling by using NetBeans.  (0) 2011.04.28
Java method의 크기 제한 - 64K  (0) 2011.03.25
:
Posted by 뽀기
2011. 5. 2. 18:00

Use of String in Java 그거/Java2011. 5. 2. 18:00


So, when the String can be fully resolved at compile time, the concatenation operator is more

efficient than using a StringBuffer. But when the String cannot be resolved at compile time, the

concatenation operator is less efficient than using a StringBuffer.

 
String 에 들어갈 문자열이 컴파일 시점에 완전히 결정이 된다면 concatenation 연산이 StringBuffer를 사용하는 것 보다 훨씬 효율적이다. 
하지만, 그렇지 못할 경우는 StringBuffer를 사용하는게 더 낫다.

String str = "HI~ " + "Lucky " + "!!!";


이건 컴파일 시점에

String str = "HI~ Lucky !!!";


이렇게 된다는 얘기.
누구나 다~~ 알고 있는 얘기. ㅋㅋ
저렇게 코딩하는 사람은 없다는 얘기! ㅋ

 
:
Posted by 뽀기
2011. 3. 25. 14:39

Java method의 크기 제한 - 64K 그거/Java2011. 3. 25. 14:39

XML 문자열 파싱과 관련해서 테스트할게 있어서,

Test class를 하나 만들고. XML 내용을 전부 긁어서 StringBuilder 로 하나의 문자열로 만들었다.

어라? 메소드 선언한 부분에 에러가 있다 -_-;


이건 뭥미.. 하고 찾아보니..

메소드의 크기가 64K 를 넘으면 안된단다.  

Test class 라인이 21852 였으니.. 게다가 XML 을 긁어서 넣어놨으니. 오죽 컸을까....

그래도. 헐~~~ 이다. ㅋㅋ 

해결방법은.. 사이즈를 64K 밑으로 줄이는 수밖에는 ㅋㅋㅋ
:
Posted by 뽀기
eclipse helios 를 설치한 후에


Failed to create the Java virtual machine


요따우 메세지가 나오면서 eclipse 가 실행이 안될때는 아래와 같이 조치하면 된당.

1. eclipse 가 설치된 디렉토리에서 eclipse.ini 파일을 notepad 로 연다.

2. 아래 옵션을 추가해준다.

   -vm
    C:\Program Files\Java\jdk1.6.0_21\bin\javaw.exe

3. 그래도 안되면 아래 옵션을 변경한다.

   256M
   -showsplash
  org.eclipse.platform
   --launcher.XXMaxPermSize
   256m

4. 변경된 eclipse.ini 파일

-startup
plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
128M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
128m
--launcher.defaultAction
openFile
-vm
C:\Program Files\Java\jdk1.6.0_21\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
:
Posted by 뽀기