开发者

Spring: inject byte array into ArrayList

开发者 https://www.devze.com 2023-02-12 15:34 出处:网络
what is the co开发者_StackOverflowrrect way of injecting a byte array into an arraylist? private ArrayList<byte[]> bytes;

what is the co开发者_StackOverflowrrect way of injecting a byte array into an arraylist?

private ArrayList<byte[]> bytes;

<property name="bytes">
<list>
    <value>0x03,0x4d</value>
</list>
</property>

does not work, as every character (0,x,0,3) is converted into a single byte. I also tried encoding like &#03;, but that doesn't work either.

One workaround would be converting to integer first an then manually convert back to byte in the bean, but that is not too pretty.

Any idea?

Regards


There is a built-in ByteArrayPropertyEditor, but according to the Javadoc, it only converts Strings into corresponding byte array:

Editor for byte arrays. Strings will simply be converted to their corresponding byte representations.

Maybe you should write your own property editor to convert arbitrary representation of byte[] into list?


Here's a FactoryBean to create your byte array:

public class ByteArrayFactoryBean extends AbstractFactoryBean<byte[]>{

    @Override
    public Class<?> getObjectType(){
        return byte[].class;
    }

    private String data;

    @Required
    public void setData(final String data){
        this.data = data;
    }

    @Override
    protected byte[] createInstance() throws Exception{
        final String[] tokens = data.split("\\s*,\\s*");
        final byte[] output = new byte[tokens.length];
        for(int i = 0; i < tokens.length; i++){
            output[i] = Byte.decode(tokens[i]).byteValue();
        }
        return output;
    }

}

Usage:

<bean class="foo.bar.SomeBean">
    <property name="bytes">
        <list>
            <bean class="foo.bar.ByteArrayFactoryBean">
                <property name="data" value="0x03,0x4d" />
            </bean>
        </list>
    </property>
</bean>

(Registering a PropertyEditor would be more correct, but also more work)


But if I understand your comments right, your actual problem is that you don't know how to write a String with exotic bytes? You can use Unicode escapes:

System.out.println("H\u00e4\u00e4\u00e4\u00e4\u00e4hhh???");

Output:

Hääääähhh???

You can of course also use this syntax in Spring XML files.

0

精彩评论

暂无评论...
验证码 换一张
取 消