instanciation error with Arraylist and String

28 views
Skip to first unread message

thfa...@gmail.com

unread,
Mar 12, 2013, 4:12:48 AM3/12/13
to objene...@googlegroups.com
Hello all
I try to use objenesis to create some objects.

I have some problems with ArrayList and String

For arraylist
        Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer
        ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(ArrayList.class);
        Object o1 = thingyInstantiator.newInstance();

That work but when i want to add elements to the created list ((ArrayList) o1).add("aaa")) i have npe error
Exception in thread "main" java.lang.NullPointerException
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:186)
at java.util.ArrayList.add(ArrayList.java:411)
at instanciator.TestObjenesisHelper.main(TestObjenesisHelper.java:41)

I have the same type of error when i want to put data in a string created by Objenesis



My system version is the following
java version "1.7.0_15"
OpenJDK Runtime Environment (IcedTea7 2.3.7) (7u15-2.3.7-0ubuntu1~12.10.1)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)


I don't know if the problem i with my use of Objenesis or from my system?


Thanks in advance

Thierry

Bubble

unread,
Mar 12, 2013, 11:51:41 AM3/12/13
to objene...@googlegroups.com
Hello, Thierry,

The behavior you're describing is actually expected. Objects instantiated using Objenesis don't have the constructor called, so they're not ready to be used in the same way as if you created the object directly or using Java Reflection. In your case, since the constructor wasn't called, the ArrayList doesn't have internal structures properly initialized.

Objenesis is for very specific, advanced usage when you need plain objects without executing the constructor code, like for testing mocks, where you don't really need to care about the internal state of the object, or for custom serialization, where you initialize the object in an alternative way that bypasses the constructor.

If you just need a generic way to create your ArrayList, just use Java Reflection.

Kind regards,
Leonardo Mesquita


--
 
---
You received this message because you are subscribed to the Google Groups "Objenesis developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to objenesis-de...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages