Jörg Henne wrote:
Hi,
Emmanuel Lecharny schrieb:
Hi,
I don't think that the line 48 in StringTools is related to 1.5. It's
just a way to get the charSet, considering that it will work for 1.4,
but will return a different result.
Can you confirm this assertion, Jörg?
as I see it, Charset.defaultCharset() is available only since 1.5 (see
its @since annotation). Having this constant initializer there, causes
at least a compile-time dependency on 1.5. I haven't tried, but I don't
see why it would not also cause a run-time dependency.
My recommendatil would be this:
private static String defaultCharset;
/**
* @return The default charset
*/
public static final String getDefaultCharsetName()
{
if (null == defaultCharset)
try {
Method method = Charset.class.getMethod("defaultCharset", new
Class[0]);
defaultCharset = ((Charset) method.invoke(null, new
Object[0])).name();
} catch (Exception e) {
// fall back to olg method
defaultCharset = new OutputStreamWriter(new
ByteArrayOutputStream())
.getEncoding();
}
return defaultCharset;
}
Doing away with the reflection is also possible: simply catching
NoSuchMethodError should allow a graceful fallback to the old method,
too. However, this comes at the price of a compile-time dependency on 1.5.
+1 I like the use of reflection here btw.
Sounds like the 1.5 dependency is Charset from java.nio.charset.Charset.
Why not go all the way and dynamically load the class itself and call
the method on it? Meaning why directly reference Charset at all?
> private static String defaultCharset;
> /**
> * @return The default charset
> */
> public static final String getDefaultCharsetName()
> {
> if (null == defaultCharset)
> try {
Class clazz = Class.forName( "java.nio.charset.Charset" );
> Method method = clazz.getMethod("defaultCharset", new
> Class[0]);
> defaultCharset = ((Charset) method.invoke(null, new
> Object[0])).name();
> } catch (Exception e) {
> // fall back to olg method
> defaultCharset = new OutputStreamWriter(new
> ByteArrayOutputStream())
> .getEncoding();
> }
> return defaultCharset;
> }
This would lift the compile dep on 1.5.
Regards,
Alex