java.util.Properties를 HashMap으로 변환
Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>(properties);// why wrong?
java.util.Properties
의 구현이며 java.util.Map
And java.util.HashMap
의 생성자 는 Map
형식 매개 변수를 받습니다 . 그렇다면 명시 적으로 변환해야하는 이유는 무엇입니까?
이는 Properties
extendsHashtable<Object, Object>
(차례로를 구현하기 때문입니다 Map<Object, Object>
). 당신은 그것을 Map<String, String>
. 따라서 호환되지 않습니다.
지도에 문자열 속성을 하나씩 공급해야합니다.
예를 들면 :
for (final String name: properties.stringPropertyNames())
map.put(name, properties.getProperty(name));
이를위한 효율적인 방법은 다음과 같이 일반 맵으로 캐스트하는 것입니다.
Properties props = new Properties();
Map<String, String> map = (Map)props;
Map<Object, Object>
이것은를 원시 맵으로 변환하며 컴파일러에 대해 "정상"입니다 (경고 만 해당). 우리가 원시가 있으면 Map
그것을 캐스팅됩니다 Map<String, String>
그것은 또한 (다른 경고) "OK"가 될 것이다. 주석으로 무시할 수 있습니다.@SuppressWarnings({ "unchecked", "rawtypes" })
이것은 JVM에서 객체가 실제로 제네릭 유형을 갖지 않기 때문에 작동합니다. 제네릭 타입은 컴파일 타임에 확인하는 트릭 일뿐입니다.
일부 키 또는 값이 문자열이 아닌 경우 ClassCastException
오류가 발생합니다. 현재 Properties
구현에서는 super Hashtable<Object,Object>
의 변경 가능한 호출 메서드를 사용하지 않는 한 발생 가능성이 거의 없습니다 Properties
.
따라서 Properties 인스턴스로 불쾌한 일을하지 않으면 이것이 갈 길입니다.
Google Guava를 사용할 수 있습니다.
com.google.common.collect.Maps.fromProperties (Properties)
이것은 어떤가요?
Map properties = new Properties();
Map<String, String> map = new HashMap<String, String>(properties);
경고가 발생하지만 반복없이 작동합니다.
자바 8 방식 :
properties.entrySet().stream().collect(
Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue().toString()
)
);
Properties
구현 Map<Object, Object>
하지 않습니다 Map<String, String>
.
이 생성자를 호출하려고합니다.
public HashMap(Map<? extends K,? extends V> m)
...와 K
와 V
모두 같은 String
.
그러나 Map<Object, Object>
그렇지 않습니다 Map<? extends String, ? extends String>
... 그것은 문자열이 아닌 키와 값을 포함 할 수 있습니다.
이것은 작동합니다.
Map<Object, Object> map = new HashMap<Object, Object>();
...하지만 그것은 당신에게 유용하지 않을 것입니다.
근본적 Properties
으로 HashTable
... 의 하위 클래스로 만들어서는 안됩니다 . 그게 문제입니다. v1 이후로 의도에 어긋나더라도 항상 비 문자열 키와 값을 저장할 수있었습니다. 컴포지션이 대신 사용 되었다면 API는 문자열 키 / 값으로 만 작동 할 수 있었고 모두 잘되었을 것입니다.
다음과 같은 것을 원할 수 있습니다.
Map<String, String> map = new HashMap<String, String>();
for (String key : properties.stringPropertyNames()) {
map.put(key, properties.getProperty(key));
}
다음 Guava API를 사용합니다. com.google.common.collect.Maps # fromProperties
Properties properties = new Properties();
Map<String, String> map = Maps.fromProperties(properties);
객체에 항목 만 포함되어 있다는 것을 알고 있는 경우 원시 유형을 사용할 수 있습니다.Properties
<String, String>
Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>((Map) properties);
The problem is that Properties
implements Map<Object, Object>
, whereas the HashMap
constructor expects a Map<? extends String, ? extends String>
.
This answer explains this (quite counter-intuitive) decision. In short: before Java 5, Properties
implemented Map
(as there were no generics back then). This meant that you could put any Object
in a Properties
object. This is still in the documenation:
Because
Properties
inherits fromHashtable
, theput
andputAll
methods can be applied to aProperties
object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are notString
s. ThesetProperty
method should be used instead.
To maintain compatibility with this, the designers had no other choice but to make it inherit Map<Object, Object>
in Java 5. It's an unfortunate result of the strive for full backwards compatibility which makes new code unnecessarily convoluted.
If you only ever use string properties in your Properties
object, you should be able to get away with an unchecked cast in your constructor:
Map<String, String> map = new HashMap<String, String>( (Map<String, String>) properties);
or without any copies:
Map<String, String> map = (Map<String, String>) properties;
this is only because the constructor of HashMap requires an arg of Map generic type and Properties implements Map.
This will work, though with a warning
Properties properties = new Properties();
Map<String, String> map = new HashMap(properties);
First thing,
Properties class is based on Hashtable and not Hashmap. Properties class basically extends Hashtable
There is no such constructor in HashMap class which takes a properties object and return you a hashmap object. So what you are doing is NOT correct. You should be able to cast the object of properties to hashtable reference.
i use this:
for (Map.Entry<Object, Object> entry:properties.entrySet()) {
map.put((String) entry.getKey(), (String) entry.getValue());
}
참고URL : https://stackoverflow.com/questions/17209260/converting-java-util-properties-to-hashmapstring-string
'development' 카테고리의 다른 글
클래스의 pthread 함수 (0) | 2020.10.13 |
---|---|
IntelliJ는 '프로그램을 실행할 수 없습니다.'/ path / to / tomcat / bin / catalina.sh '오류 = 13 권한이 거부되었습니다. (0) | 2020.10.13 |
HTML Bold 태그의 대안 (0) | 2020.10.13 |
패키지 이름에서 애플리케이션 이름 가져 오기 (0) | 2020.10.13 |
여러 줄을 쉼표로 구분하여 한 줄로 바꾸기 (Perl / Sed / AWK) (0) | 2020.10.13 |