'Language/JAVA'에 해당되는 글 57건

  1. 2014.12.01 Java Reflection - Methods
  2. 2014.12.01 Java Reflection - Fields
  3. 2014.12.01 Java Reflection - Constructors
  4. 2014.12.01 Java Reflection - Classes
  5. 2014.12.01 Java Reflection Tutorial
  6. 2014.11.27 JAVA JSON 라이브러리 Jackson 사용법
  7. 2014.11.14 serialVersionUID 용도
  8. 2014.11.14 How to get file resource from Maven src/test/resources/ folder in JUnit test?
  9. 2014.11.14 Class.getResource vs. ClassLoader.getResource
  10. 2014.11.11 [Apache Commons]Configuration

Java Reflection - Methods

Language/JAVA 2014. 12. 1. 11:40

Using Java Reflection you can inspect the methods of classes and invoke them at runtime. This is done via the Java class java.lang.reflect.Method. This text will get into more detail about the Java Method object.

Obtaining Method Objects

The Method class is obtained from the Class object. Here is an example:

Class aClass = ...//obtain class object
Method[] methods = aClass.getMethods();

The Method[] array will have one Method instance for each public method declared in the class.

If you know the precise parameter types of the method you want to access, you can do so rather than obtain the array all methods. This example returns the public method named "doSomething", in the given class which takes a Stringas parameter:

Class  aClass = ...//obtain class object
Method method =
    aClass.getMethod("doSomething", new Class[]{String.class});

If no method matches the given method name and arguments, in this case String.class, aNoSuchMethodException is thrown.

If the method you are trying to access takes no parameters, pass null as the parameter type array, like this:

Class  aClass = ...//obtain class object
Method method =
    aClass.getMethod("doSomething", null);

Method Parameters and Return Types

You can read what parameters a given method takes like this:

Method method = ... // obtain method - see above
Class[] parameterTypes = method.getParameterTypes();

You can access the return type of a method like this:

Method method = ... // obtain method - see above
Class returnType = method.getReturnType();

Invoking Methods using Method Object

You can invoke a method like this:

//get method that takes a String as argument
Method method = MyObject.class.getMethod("doSomething", String.class);

Object returnValue = method.invoke(null, "parameter-value1");

The null parameter is the object you want to invoke the method on. If the method is static you supply null instead of an object instance. In this example, if doSomething(String.class) is not static, you need to supply a validMyObject instance instead of null;

The Method.invoke(Object target, Object ... parameters) method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the method you are invoking. In this case it was a method taking a String, so one String must be supplied.


출처 - http://tutorials.jenkov.com/java-reflection/methods.html


'Language > JAVA' 카테고리의 다른 글

Java Reflection - Private Fields and Methods  (0) 2014.12.01
Java Reflection - Getters and Setters  (0) 2014.12.01
Java Reflection - Fields  (0) 2014.12.01
Java Reflection - Constructors  (0) 2014.12.01
Java Reflection - Classes  (0) 2014.12.01
:

Java Reflection - Fields

Language/JAVA 2014. 12. 1. 11:39

Using Java Reflection you can inspect the fields (member variables) of classes and get / set them at runtime. This is done via the Java class java.lang.reflect.Field. This text will get into more detail about the Java Field object. Remember to check the JavaDoc from Sun out too.

Obtaining Field Objects

The Field class is obtained from the Class object. Here is an example:

Class aClass = ...//obtain class object
Field[] methods = aClass.getFields();

The Field[] array will have one Field instance for each public field declared in the class.

If you know the name of the field you want to access, you can access it like this:

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

The example above will return the Field instance corresponding to the field someField as declared in the MyObjectbelow:

public class MyObject{
  public String someField = null;

}

If no field exists with the name given as parameter to the getField() method, a NoSuchFieldException is thrown.

Field Name

Once you have obtained a Field instance, you can get its field name using the Field.getName() method, like this:

Field field = ... //obtain field object
String fieldName = field.getName();

Field Type

You can determine the field type (String, int etc.) of a field using the Field.getType() method:

Field field = aClass.getField("someField");
Object fieldType = field.getType();

Getting and Setting Field Values

Once you have obtained a Field reference you can get and set its values using the Field.get() andField.set()methods, like this:

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

MyObject objectInstance = new MyObject();

Object value = field.get(objectInstance);

field.set(objetInstance, value);

The objectInstance parameter passed to the get and set method should be an instance of the class that owns the field. In the above example an instance of MyObject is used, because the someField is an instance member of the MyObject class.

It the field is a static field (public static ...) pass null as parameter to the get and set methods, instead of theobjectInstance parameter passed above.



출처 - http://tutorials.jenkov.com/java-reflection/fields.html


'Language > JAVA' 카테고리의 다른 글

Java Reflection - Getters and Setters  (0) 2014.12.01
Java Reflection - Methods  (0) 2014.12.01
Java Reflection - Constructors  (0) 2014.12.01
Java Reflection - Classes  (0) 2014.12.01
Java Reflection Tutorial  (0) 2014.12.01
:

Java Reflection - Constructors

Language/JAVA 2014. 12. 1. 11:39

Using Java Reflection you can inspect the constructors of classes and instantiate objects at runtime. This is done via the Java class java.lang.reflect.Constructor. This text will get into more detail about the Java Constructorobject.

Obtaining Constructor Objects

The Constructor class is obtained from the Class object. Here is an example:

Class aClass = ...//obtain class object
Constructor[] constructors = aClass.getConstructors();

The Constructor[] array will have one Constructor instance for each public constructor declared in the class.

If you know the precise parameter types of the constructor you want to access, you can do so rather than obtain the array all constructors. This example returns the public constructor of the given class which takes a String as parameter:

Class aClass = ...//obtain class object
Constructor constructor =
        aClass.getConstructor(new Class[]{String.class});

If no constructor matches the given constructor arguments, in this case String.class, aNoSuchMethodException is thrown.

Constructor Parameters

You can read what parameters a given constructor takes like this:

Constructor constructor = ... // obtain constructor - see above
Class[] parameterTypes = constructor.getParameterTypes();

Instantiating Objects using Constructor Object

You can instantiate an object like this:

//get constructor that takes a String as argument
Constructor constructor = MyObject.class.getConstructor(String.class);

MyObject myObject = (MyObject)
        constructor.newInstance("constructor-arg1");

The Constructor.newInstance() method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the constructor you are invoking. In this case it was a constructor taking a String, so one String must be supplied.


출처 - http://tutorials.jenkov.com/java-reflection/constructors.html


'Language > JAVA' 카테고리의 다른 글

Java Reflection - Methods  (0) 2014.12.01
Java Reflection - Fields  (0) 2014.12.01
Java Reflection - Classes  (0) 2014.12.01
Java Reflection Tutorial  (0) 2014.12.01
JAVA JSON 라이브러리 Jackson 사용법  (0) 2014.11.27
:

Java Reflection - Classes

Language/JAVA 2014. 12. 1. 11:38

Using Java Reflection you can inspect Java classes at runtime. Inspecting classes is often the first thing you do when using Reflection. From the classes you can obtain information about

plus a lot more information related to Java classes. For a full list you should consult the JavaDoc for java.lang.Class. This text will briefly touch upon all accessing of the above mentioned information. Some of the topics will also be examined in greater detail in separate texts. For instance, this text will show you how to obtain all methods or a specific method, but a separate text will show you how to invoke that method, how to find the method matching a given set of arguments if more than one method exists with the same name, what exceptions are thrown from method invocation via reflection, how to spot a getter/setter etc. The purpose of this text is primarily to introduce the Class object and the information you can obtain from it.

The Class Object

Before you can do any inspection on a class you need to obtain its java.lang.Class object. All types in Java including the primitive types (int, long, float etc.) including arrays have an associated Class object. If you know the name of the class at compile time you can obtain a Class object like this:

    Class myObjectClass = MyObject.class

If you don't know the name at compile time, but have the class name as a string at runtime, you can do like this:

String className = ... //obtain class name as string at runtime Class class = Class.forName(className);

When using the Class.forName() method you must supply the fully qualified class name. That is the class name including all package names. For instance, if MyObject is located in package com.jenkov.myapp then the fully qualified class name is com.jenkov.myapp.MyObject

The Class.forName() method may throw a ClassNotFoundException if the class cannot be found on the classpath at runtime.

Class Name

From a Class object you can obtain its name in two versions. The fully qualified class name (including package name) is obtained using the getName() method like this:

    Class aClass = ... //obtain Class object. See prev. section
    String className = aClass.getName();

If you want the class name without the pacakge name you can obtain it using the getSimpleName() method, like this:

    Class  aClass          = ... //obtain Class object. See prev. section
    String simpleClassName = aClass.getSimpleName();

Modifiers

You can access the modifiers of a class via the Class object. The class modifiers are the keywords "public", "private", "static" etc. You obtain the class modifiers like this:

  Class  aClass = ... //obtain Class object. See prev. section
  int modifiers = aClass.getModifiers();

The modifiers are packed into an int where each modifier is a flag bit that is either set or cleared. You can check the modifiers using these methods in the class java.lang.reflect.Modifier:

    Modifier.isAbstract(int modifiers)
    Modifier.isFinal(int modifiers)
    Modifier.isInterface(int modifiers)
    Modifier.isNative(int modifiers)
    Modifier.isPrivate(int modifiers)
    Modifier.isProtected(int modifiers)
    Modifier.isPublic(int modifiers)
    Modifier.isStatic(int modifiers)
    Modifier.isStrict(int modifiers)
    Modifier.isSynchronized(int modifiers)
    Modifier.isTransient(int modifiers)
    Modifier.isVolatile(int modifiers)

Package Info

You can obtain information about the package from a Class object like this:

Class  aClass = ... //obtain Class object. See prev. section
Package package = aClass.getPackage();

From the Package object you have access to information about the package like its name. You can also access information specified for this package in the Manifest file of the JAR file this package is located in on the classpath. For instance, you can specify package version numbers in the Manifest file. You can read more about the Packageclass here: java.lang.Package

Superclass

From the Class object you can access the superclass of the class. Here is how:

Class superclass = aClass.getSuperclass();

The superclass class object is a Class object like any other, so you can continue doing class reflection on that too.

Implemented Interfaces

It is possible to get a list of the interfaces implemented by a given class. Here is how:

Class  aClass = ... //obtain Class object. See prev. section
Class[] interfaces = aClass.getInterfaces();

A class can implement many interfaces. Therefore an array of Class is returned. Interfaces are also represented byClass objects in Java Reflection.

NOTE: Only the interfaces specifically declared implemented by a given class is returned. If a superclass of the class implements an interface, but the class doesn't specifically state that it also implements that interface, that interface will not be returned in the array. Even if the class in practice implements that interface, because the superclass does.

To get a complete list of the interfaces implemented by a given class you will have to consult both the class and its superclasses recursively.

Constructors

You can access the constructors of a class like this:

 Constructor[] constructors = aClass.getConstructors();

Constructors are covered in more detail in the text on Constructors.

Methods

You can access the methods of a class like this:

 Method[] method = aClass.getMethods();

Methods are covered in more detail in the text on Methods.

Fields

You can access the fields (member variables) of a class like this:

 Field[] method = aClass.getFields();

Fields are covered in more detail in the text on Fields.

Annotations

You can access the class annotations of a class like this:

 Annotation[] annotations = aClass.getAnnotations();

Annotations are covered in more detail in the text on Annotations.



출처 - http://tutorials.jenkov.com/java-reflection/classes.html#the-class-object


'Language > JAVA' 카테고리의 다른 글

Java Reflection - Fields  (0) 2014.12.01
Java Reflection - Constructors  (0) 2014.12.01
Java Reflection Tutorial  (0) 2014.12.01
JAVA JSON 라이브러리 Jackson 사용법  (0) 2014.11.27
serialVersionUID 용도  (0) 2014.11.14
:

Java Reflection Tutorial

Language/JAVA 2014. 12. 1. 11:37

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

Java Reflection is quite powerful and can be very useful. For instance, when mapping objects to tables in a database at runtime, like Butterfly Persistence does. Or, when mapping the statements in a script language to method calls on real objects at runtime, like Butterfly Container does when parsing its configuration scripts.

There are already numerous Java Reflection Tutorials on the internet. However, most of them, including Sun's own Java Reflection tutorial, only scratch the surface of Java Reflection and its possibilities.

This tutorial will get into Java reflection in more depth than most of the tutorials I have seen. It will explain the basics of Java Reflection including how to work with arrays, annotations, generics and dynamic proxies, and do dynamic class loading and reloading. It will also show you how to do more specific tasks, like reading all getter methods of a class, or accessing private fields and methods of a class. This tutorial will also clear up some of the confusion out there about what Generics information is available at runtime. Some people claim that all Generics information is lost at runtime. This is not true.

This tutorial describes the version of Java Reflection found in Java 6.

Java Reflection Example

Here is a quick Java Reflection example to show you what using reflection looks like:

Method[] methods = MyObject.class.getMethods();

for(Method method : methods){
    System.out.println("method = " + method.getName());
}

This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.

Exactly how all this works is explained in further detail throughout the rest of this tutorial (in other texts).

Table of Contents

You can find a list of all the topics covered in this tutorial at the top left of the page. This list is repeated on all pages in this tutorial.


출처 - http://tutorials.jenkov.com/java-reflection/index.html

:

JAVA JSON 라이브러리 Jackson 사용법

Language/JAVA 2014. 11. 27. 15:19

참조 :  
1. http://jackson.codehaus.org/
2. http://wiki.fasterxml.com/JacksonInFiveMinutes

라이브러리 다운로드
http://wiki.fasterxml.com/JacksonDownload
jackson-core, jackson-databind, jackson-annotations 를 다운 받음.

Jackson 에서 JSON 처리에 제공하는 방법
1. Streaming API
     성능이 빠름.
2. Tree Model
     일반적인 XML처럼 노드형태로 Json 데이터를 다룸. 유연성이 가장 좋음. 입맛대로 구성할 수 있음.
3. Data Binding
     POJO 기반의 가자 객체들을 JSON으로 변환함.
   -Simple data Binding : 자바클래스 내의 Map, List, String, 숫자형, Boolean, null 형의 데이터들을 JSON으로 변환함.
   -Full data binding : Simple data Binding에서 제공하는것들을 포함하고 자바 빈타입에서 제공하는 데이터들도 JSON으로 변환함.


소스
* 공식사이트에 있는 import 패키지 이름이 버전업되면서 변경됐음.(2013-05-22)

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
 
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
 
 
public class testJacksonJSON {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
 
         
        try {
 
            ObjectMapper mapper = new ObjectMapper(); // 재사용 가능하고 전체코드에서 공유함.
 
 
            String user_json = "{\"name\" : { \"first\" : \"Joe\", \"last\" : \"Sixpack\" }, "
                    " \"gender\" : \"MALE\", "
                    " \"verified\" : false, "
                    " \"userImage\" : \"Rm9vYmFyIQ==\" " "      } ";
 
            User user = mapper.readValue(user_json, User.class);
             
            System.out.println("First name : " + user.getName().getFirst());
            System.out.println("Last name : " + user.getName().getLast());
            System.out.println("Gender : " + user.getGender());
            System.out.println("Verified : " + user.isVerified());
 
            user.getName().setFirst("ChangeJoe");
            user.getName().setLast("ChangeSixpack");
             
            String jsonStr = mapper.writeValueAsString(user);
            System.out.println("Simple Binding : "+jsonStr);
             
            //직접 raw 데이터를 입력해서 JSON형태로 출력하는 방법.
            Map<string,object> userData = new HashMap<string,object>();
            Map<string,string> nameStruct = new HashMap<string,string>();
            nameStruct.put("first""RawJoe");
            nameStruct.put("last""Sixpack");
            userData.put("name", nameStruct);
            userData.put("gender""MALE");
            userData.put("verified", Boolean.FALSE);
            userData.put("userImage""Rm9vYmFyIQ==");
             
            jsonStr = mapper.writeValueAsString(userData);
            System.out.println("Raw Data : "+jsonStr);
             
            //Tree 모델 예제
            ObjectMapper m = new ObjectMapper();
            // mapper.readTree(source), mapper.readValue(source, JsonNode.class); 둘중 하나 사용가능.
            JsonNode rootNode = m.readTree(user_json);
 
            JsonNode nameNode = rootNode.path("name");
            String lastName = nameNode.path("last").textValue();
            ((ObjectNode)nameNode).put("last""inputLast");
             
            jsonStr = m.writeValueAsString(rootNode);
            System.out.println("Tree Model : "+jsonStr);
             
             
            //Streaming API 예제
            JsonFactory f = new JsonFactory();
             
            OutputStream outStr = System.out;
 
            JsonGenerator g = f.createJsonGenerator(outStr);
 
            g.writeStartObject();
            g.writeObjectFieldStart("name");
            g.writeStringField("first""StreamAPIFirst");
            g.writeStringField("last""Sixpack");
            g.writeEndObject(); // 'name' 필드용.
            g.writeStringField("gender""MALE");
            g.writeBooleanField("verified"false);
            g.writeFieldName("userImage");
            g.writeEndObject();
            g.close(); // 사용한 다음 close해줘서 output에 있는 내용들을 flush해야함.
             
             
        catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (IOException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
        }
         
         
    }
 
}
 
class User {
    public enum Gender { MALE, FEMALE };
 
    public static class Name {
      private String _first, _last;
 
      public String getFirst() { return _first; }
      public String getLast() { return _last; }
 
      public void setFirst(String s) { _first = s; }
      public void setLast(String s) { _last = s; }
    }
 
    private Gender _gender;
    private Name _name;
    private boolean _isVerified;
    private byte[] _userImage;
 
    public Name getName() { return _name; }
    public boolean isVerified() { return _isVerified; }
    public Gender getGender() { return _gender; }
    public byte[] getUserImage() { return _userImage; }
 
    public void setName(Name n) { _name = n; }
    public void setVerified(boolean b) { _isVerified = b; }
    public void setGender(Gender g) { _gender = g; }
    public void setUserImage(byte[] b) { _userImage = b; }
}
</string,string></string,string></string,object></string,object>


출처 - http://arisu1000.tistory.com/27710

:

serialVersionUID 용도

Language/JAVA 2014. 11. 14. 15:00


serialversionutil-civan.zip


1. Serialization 이란?

 

  모든 데이터의 흐름은 바이트 전송으로 이루어 집니다. 이것은 객체도 마찬가진데, 이때 사용되는 개념이 Serialization 이라는 것이고 자바에서는 java.io.Serializable 이라는 interface입니다.

이것을 사용하는 방법은 implements Serializable 이라고 class명 옆에다 추가만 해주면 됩니다. 그런데, 클래서를 선언하면 static final long 타입의 serialVersionUID 상수를 선언하라는 경고문구를 
이클립스의 노란 warning 아이콘과 더불어 확인 할 수 있습니다.

 

2. serialVersionUID 용도는?

 

만일 serialVersionUID를 지정하지 않으면 실행시점에서 JVM이 디폴트 값을 산정하게 되며, 
그 알고리즘은 Java(TM) Object Serialization Specification 정의된 것을 따른다고 합니다. 
한마디로 굳이 신경 쓸필요는 없다는 뜻이고 이클립스내에서 이 경고아이콘을 제외하도록 설정할 수도 있습니다.

그러나 모든 serialization이 필요한 클래스에는 명시적으로 serialVersionUID를 선언해줄것을 강력하게 권유하고 있는데 그 이유는 디폴트 serialVersionUID 계산은 클래스의 세부 사항을 매우 민감하게 반영하기 때문에 컴파일러 구현체에 따라서 달라질 수 있어 deserialization(serialization 했던 객체를 복구하는 과정)과정에서 예상하지 못한 InvalidClassExceptions을 유발할 수 있다 라는 것이 그 이유입니다.

즉 서로 다른 자바 컴파일러 구현체 사이에서도 동일한 serialVersionUID값을 얻기 위해서는 명시적으로 serialVersionUID값을 선언해야 하며 가능한 serialVersionUID을 private으로 선언하라는 것입니다.

 

3. 쉽게하는 방법은?

 

그러나, 이것을 간단히 할 수 있는 방법은 serialver.exe를 사용하는 것입니다.

첨부파일을 압축을 풀고 이클립스 플러그인 디렉토리에 넣어두면 자동생성 플러그인 설치는 끝
3.3에서도 이상없이 작동한다. 사용방법은 다음과 같다.
파일을 선택 마우스 오른클릭하면
Add serialVersionUID 라는 메뉴가 추가 되어 있는것을 확인할 수 있다. 



import java.io.Serializable;

public class APIJson implements Serializable {

 /**
  *   아래 참조....
  */   
 private static final long serialVersionUID = 5005432000206295213L;

}




출처 - http://softlife.tistory.com/category/%EA%B0%9C%EB%B0%9C%EB%8F%84%EA%B5%AC/Eclipse

:

How to get file resource from Maven src/test/resources/ folder in JUnit test?

Language/JAVA 2014. 11. 14. 11:31

Maven standard directory layout guide us to place any non-Java files for testing undersrc/test/resources/ folder. They are automatically copied over to target/test-classes/ folder during test phase.

Image you have the following folder layout:

src/
   main/
      java/
         SomeClass.java
   test/
      java/
         SomeClassTest.java
      resources/
         sample.txt

The question is how to reach test file resource from JUnit test method.

Test file existence 

The basically you should test whether required test file resource does exists:

@Test
public void testStreamToString() {
   assertNotNull("Test file missing", 
               getClass().getResource("/sample.txt"));
   ...
}

Test file to stream 

Please note how getResource() argument value looks. Test class getResource() will resolve/sample.txt properly to /target/test-classes/sample.txt.

You might need to get InputStream from file resource which is easy to done with help of sister methodgetResourceAsStream():

// JDK7 try-with-resources ensures to close stream automatically
try (InputStream is = getClass().getResourceAsStream("/sample.txt")) {
        int Byte;       // Byte because byte is keyword!
        while ((Byte = is.read()) != -1 ) {
                System.out.print((char) Byte);
        }
}

Test file to File or Path 

Common is also to convert resource to java.io.File or its JDK7 successor java.nio.file.Path (from so-called NIO.2). I present Path example to print last modification time of test resource filesrc/test/resources/sample.txt:

URL resourceUrl = getClass().
getResource("/sample.txt");
Path resourcePath = Paths.get(resourceUrl.toURI());
FileTime lmt = Files.getLastModifiedTime(resourcePath);
// prints e.g. "Tue Jul 09 16:35:51 CEST 2013"
System.out.println(new Date(lmt.toMillis()));

출처 - http://devblog.virtage.com/2013/07/how-to-get-file-resource-from-maven-srctestresources-folder-in-junit-test/

'Language > JAVA' 카테고리의 다른 글

JAVA JSON 라이브러리 Jackson 사용법  (0) 2014.11.27
serialVersionUID 용도  (0) 2014.11.14
Class.getResource vs. ClassLoader.getResource  (0) 2014.11.14
[Apache Commons]Configuration  (0) 2014.11.11
pageContext 내장 객체  (0) 2014.11.11
:

Class.getResource vs. ClassLoader.getResource

Language/JAVA 2014. 11. 14. 11:23

Java API Documentation에서 보면 


먼저 Class에 있는 getResource를 보자. Class는 일단 instance가 있어야 부를 수가 있다.  

public URL getResource(String name)

Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String).

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
  • Otherwise, the absolute name is of the following form:
       modified_package_name/name
     

    Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

설명을 살펴보면 ClassLoader에 있는 getSystemResource 메소드를 사용하는데 
resource를 나타내는 String이 '/'로 시작하면 absolute path로 하고
그렇지 않으면 this object가 포함되어 있는 package의 full path라고 한다. 

다음으로 ClassLoader를 살펴 보면 
public URL getResource(String name)
Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.

The name of a resource is a '/'-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

absolute path를 사용하게 된다. 

따라서 일반적으로는 ClassLoader보다는 Class의 getResource를 사용하는 편이 낫다고들 한다. 
ClassLoader의 Security Permission 제약도 문제가 될 수 있다 하는 사람도 있다. 
getResourceAsStream도 같은 원칙으로 적용될 수 있다. 

보통 코드를 쓸 때 instance로부터 읽을 때는
this.class.getResource("def/g.xml");
this.getClass().getResource("/abc/def/g.xml") ;
라고 쓰면 된다. 

Class로부터 읽고 싶을 때도 있어서
MyClass.class.getRosource("a.xml");
이런 식으로 쓰면 될 것이다. 

출처 - http://holycall.tistory.com/entry/ClassgetResource-vs-ClassLoadergetResource





Class.getResource() 메소드는 해당 클래스의 소스 파일 위치를 상대 루트로 설정한다.

반면, ClassLoader.getResource()/getResources() 메소드는 클래스패스의 루트를 상대 루트로 설정한다.

다음은 이와 같은 차이를 보여주는 예제이다.

package test;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

public class GetResourceExample {

 public static void main(String[] args) {
  Class<GetResourceExample> clazz = GetResourceExample.class;
  URL resource = clazz.getResource(".");
  System.out.println("resource: " + resource);

  ClassLoader classLoader = clazz.getClassLoader();
  try {
   Enumeration<URL> resources = classLoader.getResources(".");
   System.out.println("resources:");
   while (resources.hasMoreElements()) {
    URL nextElement = resources.nextElement();
    System.out.println(nextElement);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

결과는 다음과 같다.

resource: file:/D:/%ec%9e%91%ec%97%85%ec%8b%a4/Java/JavaExample/bin/test/
resources:
file:/D:/%ec%9e%91%ec%97%85%ec%8b%a4/Java/JavaExample/bin/


Class.getResource() 메소드의 경우

해당 클래스가 포함된 패키지에 따른 디렉토리를 현재 디렉토리로 함을 알 수 있다.

반면, ClassLoader.getResources() 메소드의 경우

클래스패스의 루트를 현재 디렉토리로 함을 확인할 수 있다.


출처 - http://devday.tistory.com/entry/ClassgetResource-vs-ClassLoadergetResourcegetResources

'Language > JAVA' 카테고리의 다른 글

serialVersionUID 용도  (0) 2014.11.14
How to get file resource from Maven src/test/resources/ folder in JUnit test?  (0) 2014.11.14
[Apache Commons]Configuration  (0) 2014.11.11
pageContext 내장 객체  (0) 2014.11.11
http://www.docjar.com/  (0) 2014.11.11
:

[Apache Commons]Configuration

Language/JAVA 2014. 11. 11. 16:37

http://commons.apache.org/configuration/

연구실에서 프로젝트를 할 때, DB 계정 정보 등의 설정 정보 등을 XML파일로 적어놓고 참조하려고 마음을 먹었습니다. 그래서  XML파일 읽는 코드를 한 20줄 짜고, 이 설정 정보를 java.util.Properties 에 저장하여 메모리에 유지하도록 static 하게 변수를 선언하는 등의 작업을 하였으나, 검색해보니 Apache Commons 프로젝트에 Configuration 이라는 컴포넌트가 있습니다.

구글에서 검색하니 http://twit88.com/blog/2007/09/18/xml-configuration-for-java-program/  에도 간단한 예가 나와있습니다. 어쨌든, http://commons.apache.org/configuration/userguide/user_guide.html 를 보시면 이 컴포넌트의 사용방법이 자세하게 기술되어 있습니다. 그리고 User guide의 Hierarchical Properties 항목을 보면, XML파일을 이용하는 방법이 기술되어 있습니다. 


간단히 따라해보았습니다.
먼저 conf.xml 라는 이름의 xml 설정파일을 만들었습니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <database>
        <server>
            <type>PostgreSQL</type>
            <host>localhost</host>
            <port>5432</port>
        </server>
        <user>               
            <name>coinus</name>
            <password>1124</password>
        </user>
        <database>
            <name>coinus</name>
            <charset>UTF8</charset>
        </database>
    </database>      
</config>
다음은 XMLConfiguration 를 사용해서 XML파일을 읽는 간단한 예제입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package kr.ac.uos.dmlab.config;
 
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
 
public class ConfigLoader {
     
    private static XMLConfiguration load(String file) {
        XMLConfiguration conf= null;
        try {
            conf= new XMLConfiguration("conf/conf.xml");
             
            System.out.println(conf.getString("database.server.type"));
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        return conf;
    }
     
    public static void main(String[] args) {
        load("conf/conf.xml");
    }
     
}
load()  메소드 중간에 root element인 config 밑의 database 밑의 server 밑의 'type' element의 문자열 값을 가져와서 출력하는 코드가 13 line에 있습니다. 이렇게 element의 value를 문자열이나 정수형 등으로 가져올 수 있습니다. 물론 attribute도 사용할 수 있습니다. 자세한 내용은 User Guide의 Hierarchical Properties 를 참조해주세요. ^^;;

아 그리고 Configuration 컴포넌트의 코드에서 Commons의 다른 컴포넌트들, lang, collections, logging 등이 사용됩니다. 모두 다운 받아서 추가해주어야 합니다. 현재로서는 많은 기능이 필요한 것은 아니지만, 머 훌륭한 코드들일테니 배워두어서 나쁠리 없겠죠.




출처 - http://thebasis.tistory.com/94

: