# 빅데이터로 일하는 기술 - 장동인, 한빛미디어

- 2017월 8월 독서


빅데이터로 일하는 기술
국내도서
저자 : 장동인
출판 : 한빛미디어 2014.12.16
상세보기


사내교육으로 인해 의무적으로 읽어야 하는 상황이어서 읽었지만 많은 생각이 들게 하는 책이었다.


이 책의 앞부분은 빅데이터라는 기술의 트렌드와 재미있는 주제들을 설명하고

뒷 부분에서는 기업에서 빅데이터 시스템을 구축하는 프로세스를 소개하고 설명하고 있다.


"빅데이터라는 기술의 트렌드와 재미있는 주제들" 부분에서는

DB시장이 오라클에서 하둡으로 변해가는 시대와 빅데이터 산업의 트렌드를 시작으로

빅데이터의 정의, 소셜 미디어 분석 등을 사례와 함께 설명하고 있다.


"기업에서 빅데이터 시스템을 구축하는 프로세스" 부분에서는

구축 프로세스를 소개하며

각 프로세스에서 고려되는 아주 상세한 상황들을 어떻게 해결해 나아갈 지 방향을 제시하고 있다.

단계별로 다양한 옵션들을 제시해준다.

예를 들어 하둡과 같은 저장소를 쓴다고 해도 "기존 DB를 병렬로 할 것인가 아니면 완전히 통합할 것인가"를 고민할 때

그에 따른 장단점이나 그 결정에 따른 IT 조직의 변화 등의 세부사항들에 대한 의견을 제시하고 있다.


2014년 말 책이지만 이 당시에 이러한 응용사례들이 있었다는 것에 내가 상당히 뒤쳐져 있구나를 깨닫게 했고

빅데이터 시스템을 IT운영에만 맡기기에는 그 활용도가 너무나 떨어지니

현업과 그 현업을 움직이게 할 부서가 도입 프로젝트를 총괄해야 한다는 주장은

IT부서탓만 하지말라고 하는 것 같아 통쾌하기도 했다.


# 가장 인상깊은 한 줄

p.247, "중요한 것은 처음부터 끝까지 모든 팀이 비즈니스 목적에 정렬되도록 하며, 이를 위해서 모든 팀이 서로 하는 일을 이해해야 한다는 것이다."



# 자주 쓸 것 같은 Third-party packages 메모



# 강의에서 추천


  • IPython - A better interactive Python interpreter
  • requests - Provides easy to use methods to make web requests. Useful for accessing web APIs.
  • Flask - a lightweight framework for making web applications and APIs.
  • Django - A more featureful framework for making web applications. Django is particularly good for designing complex, content heavy, web applications.
  • Beautiful Soup - Used to parse HTML and extract information from it. Great for web scraping.
  • pytest - extends Python's builtin assertions and unittest module.
  • PyYAML - For reading and writing YAML files.
  • NumPy - The fundamental package for scientific computing with Python. It contains among other things a powerful N-dimensional array object and useful linear algebra capabilities.
  • pandas - A library containing high-performance, data structures and data analysis tools. In particular, pandas provides dataframes!
  • matplotlib - a 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments.
  • ggplot - Another 2D plotting library, based on R's ggplot2 library.
  • Pillow - The Python Imaging Library adds image processing capabilities to your Python interpreter.
  • pyglet - A cross-platform application framework intended for game development.
  • Pygame - A set of Python modules designed for writing games.
  • pytz - World Timezone Definitions for Python




# Third-party packages 버전 고정법

- 하나의 서드파티 패키지도 여러개의 버전으로 나뉘고 이로인해 문제가 생기는 경우 고정해서 쓴다.

- requirements.txt 파일을 만들어서 고정할 패키지와 버전의 list를 나열한다.

beautifulsoup4==4.5.1
bs4==0.0.1
pytz==2016.7
requests==2.11.1

- 이것을 python에 반영한다.

$ pip3 install -r requirements.txt



Reference:

- https://classroom.udacity.com/courses/ud1110

# 자주 쓸 것 같은 Python Standard libraries 메모



# Python Standard library: https://docs.python.org/3/library/



# 강의에서 추천


  • csv: very convenient for reading and writing csv files
  • collections: useful extensions of the usual data types including OrderedDictdefaultdict and namedtuple
  • random: generates pseudo-random numbers, shuffles sequences randomly and chooses random items
  • string: more functions on strings. This module also contains useful collections of letters like string.digits (a string containing all characters with are valid digits).
  • re: pattern-matching in strings via regular expressions
  • math: some standard mathematical functions
  • os: interacting with operating systems
  • os.path: submodule of os for manipulating path names
  • sys: work directly with the Python interpreter
  • json: good for reading and writing json files (good for web work)




# 상황별

1. 날짜와 시간 관련: datetime

   - https://docs.python.org/3/library/datetime.html



2. 현재의 working directory 바꾸기: os

   os.chdir(path)

   - https://docs.python.org/3/library/os.html



3. csv파일 읽기: csv

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

  - https://docs.python.org/3/library/csv.html



4. zip 파일 압축해제: zipfile

with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())

   - https://docs.python.org/3/library/zipfile.html



5. 실행시간 측정: cProfile

   - https://docs.python.org/3/library/profile.html

   - 작은 수행일때는 timeit도 많이 쓴다.

      https://docs.python.org/3/library/timeit.html



Reference:

- https://classroom.udacity.com/courses/ud1110

- https://docs.python.org/3/library/

virtualenv에 OpenAI gym 설치하기(MAC OS)



1단계: virtualenv로 가서 pip 명령을 이용해 설치한다.

$ source [설치한 경로]/bin/activate

(설치폴더이름) $ pip3 install gym

이렇게 하면 minimal 로 설치가 되며 이 단계 만으로 실행할 수 있는 환경은 다음과 같다.

- algorithmic

- toy_text

- classic_control (you'll need pyglet to render though)



끝.

2단계: atari 등은 성공하면 업데이트 예정.



reference:

https://github.com/openai/gym

# Python 언어 Syntax 요약(feat. Java)

간략히 Java를 기준으로 염두해 두어야 할 것들을 정리해본다.



0. 주석(comment)

 의미 

 Python

 비고

 한줄 주석

 # Python

 // Java

 여러줄 주석

 ''' Python '''

 """ Python """

 /* Java */



1. 연산자(Operator)

 의미

 Python

 비고

 덧셈, 뺄셈, 곱셈 나눗셈 등

 아래 나열되지 않는 대부분의 것들

 Java와 동일

 - 나눗셈을 하면 Float이 된다. Java처럼 int로 나오고 싶으면 // 이렇게 두번 쓰면 된다.

 

 제곱(거듭제곱)

 ** 라는 연산기호가 있다.

 Java에서는 Math.pow()를 사용하는 편

 연산자 Convention

 덧셈, 뺄셈같은 상대적 후순위 계산은 띄어쓰기를 하고

 곱셈, 나눗셈은 띄어쓰기 하지 않는다.

 ex) 1 + 2*3




2. 자료형

 의미 

 Python

 비고

 Integer, Float

 Integer, Float으로 double이나 short, char 같은 개념을 통합했다.

 하지만 선언시 자료형을 미리 정의하지 않는다.

 float의 경우는 2진수로 표현할 수 있는 근사값 형태로 저장되는데 이 때문에 10진수를 2진수로 변환할 때 생기는 loss가 있다.

 ex) 0.1 + 0.1 + 0.1 != 0.3

 

 Boolean

 대문자로 시작하는 True, False를 쓴다.

 하지만 선언시 자료형을 미리 정의하지 않는다.

 부정을 표현할때 "!" 대신 "not" 을 쓴다.


 String

 string(immutable)

 Java와 달리 ''로도 String을 묶을 수 있다(큰따옴표, 작은따옴표 둘다 동일하게 사용)

 특이하게도 string을 곱셈할 수 있는데 "hippo" *3 하면

"hippohippohippo" 가 된다.

 

 list

 tuple(immutable), list(mutable) 두가지 형태가 built-in으로 존재한다.

 - 서로 형변환 할 수 있다.

 1. list

 - list[start_index : end_index] 라는 구역의 개념으로 slicing과 replacing이 가능하다

 - list의 요소를 쉽게 찾아볼 수 있다.

    ex) if a in some_list:

 2. tuple

 - return 인자가 여러개 일때 이 형태로 보내주는 것이고 이렇게 Unpacking이 쉽다.

 Linked-list가 속도가 낫냐 Array-list가 낫냐 같은 결정은 그리 중요하지 않다는 뜻인가 보다...

 Set

 set 라는 명칭으로 built-in 되어 있다.

 list처럼 for 문을 돌 수 있다.

 ex) for item in set:

 이제 어떤 Set을 쓰느냐는 중요하지 않은 것이다...

 Map

 dictionary 라는 명칭으로 built-in 되어 있다.

 list처럼 for 문을 돌 수 있다.

 ex) for item in set: >> key가 하나씩 된다.

 이제 어떤 Map을 쓰느냐는 중요하지 않은 것이다...



3. Built-in Method:  built-in method로 대부분 해결이 된다.

 의미

 Python

 비고

 length

 len(): 문자열의 길이, 배열의 길이 등을 잰다

 

 type check

 type(): 자료형 type을 본다

 

 type casting

 int() 등: 자료형을 casting하고 string -> int 같은 변환도 담당한다.

 

 String 변형

 String 내부 method도 있으니 찾아서 활용하면 된다.

 - .count([찾을단어]): 찾을단어가 몇번 들어갔는지...

 - etc...

 https://docs.python.org/3/library/stdtypes.html#string-methods

 List에서 max/min 값 찾기

 max() / min()

 

 정렬

 sorted()

 Quick, Merge, Bubble 뭐 이런건 의미 없구나...

 string 배열 하나로 합치기

 [join 할때 사이에 들어갈 string].join([join시킬 string 배열])

 ex) "-".join(["This", "is", "Sparta"])

      This-is-Sparta

 - 배열에 int 같은거 들어가 있으면 오류남. string-only list

 Java에서는 StringBuilder로 해결했던 편...

 string에 단어 첫글자 대문자로 변경

 [space가 들어간 string].title()

 ex) "first last".title()

       First Last

 



4. 조건문, 반복문, brace: 이것은 예제를 보는것이 낫다.

 의미

 Python 

 Java

 brace

 특정 조건에 대한 ":" 그 밑의 탭(Indentation) 들어간 것으로 구분

 {}로 묶음

 if

 if [조건]:

 if ([조건])

 for

 for item in input_list:

 for i in range(100):

 for each 처럼 쓰거나

 for (int i = 0; i < 100; i++) 처럼 쓰거나...




Reference:

- Introduction to Python: https://www.udacity.com/course/introduction-to-python--ud1110


Wrap-up "Machine learning" by Andrew Ng

I attended a online course, "Machine learning" by Andrew Ng that held in Coursera.org by Stanford Univ. Online.

I started this course to find more background theories about "Tensorflow".

However, it makes me be more interested in "Machine learning" and more curious about "Deep learning".



# Some impressive things in the course

- The professor explains the detailed algorithms with many examples.

   If I didn't understood an algorithm, I just waited and kept seeing the examples. The examples helped me understand.

- He explains the mathematical approaches of the algorithms.

   So I had to stop the video and tried to the mathematical approaches by myself.

   It took more times than I planned.

- The exercises are so difficult to make vectorized codes.

   But I think it is the most important point to imagine inner algorithms of "Tensorflow".

   I needed to practice matrix calculations in Octave to imagine vectorized codes.

- He knows the machine learning algorithm and system are difficult to understand and he said he also had felt them difficult when he learn.

   This words encouraged me.



# Wrap-up

1. Supervised Learning

    a. Linear regression

    b. Logistic regression

    c. Neural networks

    d. SVMs(Support Vector Machine)


2. Unsupervised Learning

    a. K-means

    b. PCA(Principle Component Analysis)

    c. Anomaly detection


3. Special applications / special topics

    a. Recommender systems

    b. Large scale machine learning


4. Advice on building a machine learning system

    a. Bias / Variance

    b. Regularization

    c. Deciding what to work on next

        - Evaluation of learning algoritms

        - Learning curves

        - Error analysis

        - Ceiling analysis

'Machine Learning' 카테고리의 다른 글

YOLO v3 demo webcam 돌려보기 for ubuntu(18.04)  (0) 2018.10.03
Activation functions  (0) 2017.11.30
Binomial Logistic Regression/Classification  (0) 2017.07.10
Linear Regression  (0) 2017.07.07

"시즌 1 - 딥러닝의 기본" Wrap-up

학습을 마치며 전반적 수업내용에 대한 정리를 해본다.

이 강의을 들으면서 더 깊이있는 지식이 필요하여 Coursera의 "Machine Learning" - Andrew Ng 강의을 들었고 더 잘 이해할 수 있었다.

하지만 딥러닝부분에서는 배경지식이 없어서 CNN, RNN등 에 대한 깊이있는 공부를 위해서 다른 강의를 수강해야 할 것 같다.



몇가지 인상깊은 특징을 나열해보자면

- 이 강의는 15분 내외의 짧은 동영상 강의로 되어있고

- 머신러닝이나 딥러닝의  개념설명과 TensorFlow로 구현하는 방법을 알려준다.

- 하지만 머신러닝이 빠진 타이틀에서 유추할 수 있듯이 딥러닝에 초점이 되어있다.

- TensorFlow가 많은 기능들을 지원하다보니 이론적인 이해가 덜 되어도 실습에는 무리가 없다.

- 이론적인 부분에 있어서는 생략되는 부분이 있다보니 후반부로 갈 수록 왜 그렇게 생각하고 나아가는지에 대한 공감이 어려웠다.



# Wrap-up

1. Machine learning

    a. Supervised

    b. Unsupervised


2. Linear regression

    a. hypothesis

    b. cost function

    c. Minimize cost

        - Gradient descent Algorithm

        - Convex function이 되어야 한다.

    d. Multivariable


3. Logistic regression/classification

    a. Sigmoid

    b. cost function

    c. Minimize cost

    d. Multinomial classification

    e. Softmax

    f. One-hot encoding

    g. Cross-Entropy


4. 머신러닝 관련 용어정리와 tip

    a. learning late

        - 너무 크면 Overshooting 경향

        - 너무 작으면 local minimum 경향

    b. Standardization

    c. Overfitting

    d. Regularization

    e. training / validation / test set

    f. MNIST dataset


5. Neural Networks

    a. Neural net and Activation function

    b. XOR problem

    c. forward propagation

    d. back propagation

        - 초기화를 잘 해야된다.(ex - RBM: Restricted Boatman Machine)

        - vanishing gradient problem: ReLU로 해결

    e. ReLU(Rectified Linear Unit)

        - 다른함수:  Sigmoid, Leaky ReLU, tanh, Maxout, ELU

    f. dropout

    e. ensemble


6. CNN(Convolutional Neural Networks)

    c. Convolution Layer

        - filter

        - stride

    d. Pooling Layer

        - Max pooling


7. RNN(Recurrent Neural Networks)

    a. sequence data

    b. hidden size

    c. batch size



Reference:

- http://hunkim.github.io/ml/

Binomial Logistic Regression/Classification


           X1, X2, ..., Xn

+ Linear Regression

+                Sigmoid

-------------------------

=>                  0 or 1


Logistic Classification에서 왜 Linear Regression + sigmoid를 쓰는지를 제가 이해하는 개념대로 설명합니다.

다른 이론과 차이가 있다면 아마도 그 이론이 맞고 제 이해는 틀릴 가능성이 높습니다.

이상한 점이 있다면 보충하거나 수정하겠습니다.


1. Binomial Logistic Classification을 한다는 것

classification을 한다는 것은 어떤 data들을 A group, B group, C group, ... N group으로 분류를 하는 것인데

Binomial Logistic은 이를 단순하게 모든 것은 A group, B group 으로만 분류된다고 한정하여 집중한다.

이분법적, 흑백논리.. 그런 개념이므로 Not A group == B group으로 볼수도 있고 0, 1 / True, False라는 개념으로도 이해할 수 있다.




Classification                  

Binomial Classification



2. A gourp, B group을 0, 1로 각각 생각한다.

x_data = [-3, -2, -1, 1, 2, 3]

y_data = [1, 1, 1, 0, 0, 0]

이러한 data가 있고 이를 그래프로 표현하려고 하면 X-Y 축를 그려야 한다.


    





3. Sigmoid 함수를 사용하는 이유 => 0, 1로 표현하기 위해

위의 데이터를 통해서 Y를 예측하는 그래프를 그린다면 0, 1로 결과가 나올 수 있는 Linear regression + sigmoid 함수를 이용해서 다음과 같이 추정 그래프를 그릴 수 있다.



# 빨간색 : Linear regression + sigmoid 함수 적용 예측값

# 파란색 : Linear regression 함수의 예측값 


빨간색 그래프는 X축 [-1, 1] 사이를 기준으로 실제값과 유사한(예측가능한) 그래프를 그려준다.

파란색 선의 의미는 어떤 접점을 기준으로 나누고 있지만 그 의미가 분명하지 않다.

하지만 파란색이 Y축 1에 가까운지 0에 가까운지 라는 조건으로 바라본다면 그 그래프는 빨간색과 같을 것이다.

이것이 sigmoid를 가설에 포함하여 사용하는 이유이다.

즉, sigmoid를 통해서 Y축 0과 1로 (그래서 결론은 A Group에 속합니다./ 속하지 않습니다.)예측의 결론을 낼 수 있다.



4. Linear Regression 방식을 사용하는 이유 => 다른것 써도된다. 관계가 Linear하다고 가정하는 접근이였다.

여기까지 왔다면 sigmoid에 의해 어차피 0, 1 두가지로 나누어 지는데 굳이 Linear Regression 방식이 필요한 것인가 생각이 들 것이다.

(X끼리 더하든 곱셈을 하거나 하는 그런 관계도 있을 수 있겠는데 말이다.)

그 이유는 X1, X2 두가지 변수에 대한 예측을 할때를 살펴보면 이해가 된다.


x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]

y_data = [[0], [0], [0], [1], [1], [1]]


의 data가 있을때

우선 X1과 X2의 관계 그리고 Y값 표시를 그려보자.


우리는 Y의 데이터가 검정과 빨강을 구분하는 기준이 된다는 것을 알았고 이제 Y를 예측하는 값을 그래프로 나타내면

알아보기 힘들지만 여러번의 학습을 거쳐 전반적으로 실제Y값과 추정값이 비슷한 위치로 가고 있다고 보여진다.

100 times trained

 ==>10000 times trained

시각적으로 평면 X, Y축에서 A와 B 그룹을 나눠주는 선을 긋는 것이 이해하기 쉬우므로 X1, X2에 대한 관계에 이를 표현해보자.



관계를 sigmoid 함수 0, 1일 때의 방정식으로 구하기에는 어려운 점이 있어서



Linear Regression 공식으로 구해본다.

1) Y=0 일때


2) Y=1 일때


이러한 관계식을 X1 - X2  그래프에 표시하면 다음과 같다.

1000 times trained 

10000 times trained


파란색이 학습된 경계선이며 학습을 조금 시켰을때는 검정색과 빨간색의 그 경계선이 모호했지만

학습을 많이 함에 따라서 구분짓는 경계선이 얇아지고 더 분명하게 되었다.

(기울기는 Random값에서 출발하여 다를 수 있다.)


Linear Regression 방법을 유지하는 이유는

- Gradient Descent로 cost를 계산할 수 있고

- 이처럼 관계를 계산하거나 구분하는 선을 그리는데 장점이 있다고 생각한다.



Reference:

- http://hunkim.github.io/ml/


'Machine Learning' 카테고리의 다른 글

YOLO v3 demo webcam 돌려보기 for ubuntu(18.04)  (0) 2018.10.03
Activation functions  (0) 2017.11.30
Wrap-up "Machine learning" by Andrew Ng  (0) 2017.10.13
Linear Regression  (0) 2017.07.07

Linear Regression



1. Linear한 관계(1차 방정식=직선)일 것이라고 가정하고 기계적으로 귀납적 추론을 하게 하는 방법

- X -> Y로 변화하는 관계에 대해서

 

 라는 가설을 세워 접근하는 것이다.

 물론 1차방정식을 알고 있다면 W는 기울기이고 b는 이 그래프의 수직이동 관계이다.


- X가 여러개라도

 라는 관계가 성립한다고 보는것



2. 기계적으로 귀납적 추론을 하게 하는 방법

- X, Y 자료가 있고 가설의 그래프(1차 방정식 그래프 = 직선)를 그렸을때 가설과 실제값의 차이를 보인다면

  그 차이를 최소화 할 수 있는 그래프를 찾도록 하는 것이다.

- 여기서 최소값을 찾는다는 것은 그래프의 기울기 W와 그래프의 수직이동 b 의 값을 적절히 하게 하여

  가설이 실제값에 가장 유사한 조건이 되도록 하는 것이다.



3. 최적의 조건을 찾게 하는 방법

- 가설과 실제값의 차의 제곱의 평균을 한 것을 cost 함수라고 정의하고 이 값을 최저로 만든다.

  

- 이 cost 공식을 쓸때 cost의 추이는 다음과 아래와 유사한 2차 방정식 곡선을 그리며

  0에 가장 가까운 지점을 찾아가게 되는데

  이 때 경사도를 구하여 0에 가까운 지점을 찾아가는 방법을 Gradient Descent Algorithm이라고 한다.


Reference:

- http://hunkim.github.io/ml/

- https://ko.wikipedia.org/wiki/%EC%84%A0%ED%98%95_%ED%9A%8C%EA%B7%80

  

   

Custom Annotation 만들기



Gson 이라는 클래스를 쓸때 @SerializedName("fieldName") 라는 쓰는 경우가 있고

이러한 Annotation의 원리가 궁금했다.


1. interface앞에 @를 붙여서 Annotation Interface를 선언한다.

2. Annotation을 구현한다. (Annotation 사용자의 경우)

3. Reflection을 이용하여 객체나 class에서 선언된 필드나 메소드를 찾고 적절한 동작을 구현한다.

의 순서로 접근하면 된다.



1. interface앞에 @를 붙여서 Annotation Interface를 선언한다.

@Inherited

@Documented

@Retention(RetentionPolicy.RUNTIME) // 컴파일 이후에도 JVM에 의해서 참조가 가능합니다.

//@Retention(RetentionPolicy.CLASS) // 컴파일러가 클래스를 참조할 때까지 유효합니다.

//@Retention(RetentionPolicy.SOURCE) // 어노테이션 정보는 컴파일 이후 없어집니다.

@Target({

        ElementType.PACKAGE, // 패키지 선언시

        ElementType.TYPE, // 타입 선언시

        ElementType.CONSTRUCTOR, // 생성자 선언시

        ElementType.FIELD, // 멤버 변수 선언시

        ElementType.METHOD, // 메소드 선언시

        ElementType.ANNOTATION_TYPE, // 어노테이션 타입 선언시

        ElementType.LOCAL_VARIABLE, // 지역 변수 선언시

        ElementType.PARAMETER, // 매개 변수 선언시

        ElementType.TYPE_PARAMETER, // 매개 변수 타입 선언시

        ElementType.TYPE_USE // 타입 사용시

})


public @interface CustomAnnotation {

    

    String name() default "default";

    String value() default "default";

}

- name(), value()가 attribute명이자 getter가 된다.

- default는 필드값을 안채우거나 하나만 쓸때 채워지는 값이다.

- interface위의 필드(Target, Retention 등)는 주석을 보거나 실생활에 쓰이고 있는 case를 참고하는것이 좋겠다.


1-1. 사용사례

 @Override

 package java.lang;

 ...

 @Target(ElementType.METHOD)

 @Retention(RetentionPolicy.SOURCE)

 public @interface Override {

 }

 @SerializedName

 package com.google.gson.annotations;

 ...

 @Retention(RetentionPolicy.RUNTIME)

 @Target({ElementType.FIELD})

 public @interface SerializedName {

     String value();

 }

@Test 

 package org.junit;

 ...

 @Retention(RetentionPolicy.RUNTIME)

 @Target({ElementType.METHOD})

 public @interface Test {

   Class<? extends Throwable> expected() default Test.None.class;

   long timeout() default 0L;

   public static class None extends Throwable {

        private static final long serialVersionUID = 1L;

        private None() {

        }

    }

}

- Override 주석을 보면 그 유명한 Effective Java의 저자 조슈아 블로치(Joshua Bloch)이고 Java 1.5부터 반영된것으로 보인다!!



2. Annotation을 구현한다. (Annotation 사용자의 경우)

public class CustomAnnotationImpl {

    @CustomAnnotation("aaa")

    private String name;


    @CustomAnnotation(value="ccc", name="bbb")

    private String value;


    CustomAnnotationImpl(String name, String value) {

        this.name = name;

        this.value = value;

    }


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    public String getValue() {

        return value;

    }


    public void setValue(String value) {

        this.value = value;

    }


    @CustomAnnotation("print")

    public void printNameAndValue() {

        System.out.println("name=" + name + ", value=" + value);

    }

}

- 1에서처럼 매개변수가 여러개로 선언했으나 @CustomAnnotation("aaa")인 경우는 매개변수 선언 순서상의 마지막에 할당되는 것 같다.



3. Reflection을 이용하여 객체나 class에서 선언된 필드나 메소드를 찾고 적절한 동작을 구현한다.

 Field 찾기

         for (Field field : fieldArray) {

            String fieldName = field.getName();

            CustomAnnotation testAnnotation = field.getAnnotation(CustomAnnotation.class);

            Annotation[] annotationArray = field.getDeclaredAnnotations();

            boolean isAnnotationPresent = field.isAnnotationPresent(CustomAnnotation.class);


            if (testAnnotation != null) {

                field.setAccessible(true);

                

                if (obj != null) {

                    String fieldValue = (String)field.get(obj);

                    field.set(obj, "33");

                    fieldValue = (String)field.get(obj);

                }

            }

        }

 Method 찾기

         for (Method method : methodArray) {

            String methodName = method.getName();

            CustomAnnotation testAnnotation = method.getAnnotation(CustomAnnotation.class);

            Annotation[] annotationArray = method.getDeclaredAnnotations();

            boolean isAnnotationPresent = method.isAnnotationPresent(CustomAnnotation.class);

            

            if (testAnnotation != null) {                

                if (obj != null) {

                    method.invoke(obj);

                }

            }

        }

- 하지만 Reflection은 성능이 좋지 않다는 치명적인 단점이 있다. 매개변수의 타입체킹도 런타임에 되서 위험할 수도 있고...

  잘 쓰면 괜찮다고는 하지만 그만큼 적절한가를 따져야 한다.



위 내용에 대한 코드는 github에서 확인하실 수 있습니다.

https://github.com/ndukwon/Duk_Java_library/tree/master/src/com/duk/lab/java/annotation



Reference:

- http://jdm.kr/blog/216

- https://medium.com/@ggikko/java-%EC%BB%A4%EC%8A%A4%ED%85%80-annotation-436253f395ad

- https://www.javatpoint.com/custom-annotation






'Program Languages > Java' 카테고리의 다른 글

Loop 문법과 속도  (0) 2017.06.26

+ Recent posts