InvalidClassException: класс недопустим для десериализации
Я использую библиотеку синтаксического анализатора SSA в моем проекте. Когда я вызываю основной метод одного из его классов с помощью командной строки, он отлично работает на моей машине.
Я выполняю следующую команду из командной строки:
java -Xmx800M -cp %1 edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTMPSubcategories -outputFormat "penn,typedDependenciesCollapsed" englishPCFG.ser.gz %2
Но когда я пытался использовать тот же класс в моей Java-программе, я получаю Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; edu.stanford.nlp.stats.Counter; class invalid for deserialization исключение.
Следующая строка выдает ошибку:
LexicalizedParser _parser = new LexicalizedParser("C:\englishPCFG.ser.gz");
Этот файл englishPCFG.ser.gz содержит некоторые классы или информацию, которая загружается при создании объекта типа LexicalizedParser ,
Ниже приведена трассировка стека:
Loading parser from serialized file C:\englishPCFG.ser.gz . Exception in thread "main" java.lang.RuntimeException: Invalid class in file: C:\englishPCFG.ser.gz at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromSerializedFile(LexicalizedParser.java:822) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromFile(LexicalizedParser.java:603) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.(LexicalizedParser.java:168) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.(LexicalizedParser.java:154) at com.tcs.srl.ssa.SSAInvoker.(SSAInvoker.java:21) at com.tcs.srl.ssa.SSAInvoker.main(SSAInvoker.java:53) Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; edu.stanford.nlp.stats.Counter; class invalid for deserialization at java.io.ObjectStreamClass.checkDeserialize(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromSerializedFile(LexicalizedParser.java:814) . 5 more Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; class invalid for deserialization at java.io.ObjectStreamClass.initNonProxy(Unknown Source) at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) at java.io.ObjectInputStream.readClassDesc(Unknown Source) . 17 more
Я новичок в мире Java, поэтому я не понимаю, почему возникает эта ошибка, и что я должен делать, чтобы ее избежать.
Я погуглил эту ошибку, а затем обнаружил, что эта ошибка возникает из-за некоторого несоответствия версий, которое, по-моему, похоже на адский dll Windows API. Я прав?
Кто-нибудь знает, почему возникает такая ошибка? и что мы должны сделать, чтобы избежать этого?
InvalidClassException : class invalid for deserialization
The java word for dll hell is classpath hell 😉 But that’s not your hell anyway.
Object serialization is a process of persisting java objects to files (or streams). The output format is binary. Deserialization (iaw: making java objects from serialized data) requires the same versions of the classes.
So it is possible, that you simply use an older or newer version of that Counter class. This input file should be shipped with a documentation that clearly says, which version of the parser is required. I’d investigate in that direction first.
Solution 2
It could be because the serialVersionUID of the classe has changed, and you are trying to read an object that was written with another version of the class.
You can force the version number by déclaring a serialVersionUID in your serializable class:
private static final long serialVersionUID = 1L;
Solution 3
OT: For the sake of completeness I ran into InvalidClassException . class invalid for deserialization (and this question) when solving another problem. (Since edu.stanford.nlp.stats.Counter is not anonymous, the case in this question is certainly not the same case as mine.)
I was sending a serialized class from server to client, the class had two anonymous classes. The jar with these classes was shared among server and client but for server it was compiled in Eclipse JDT, for client in javac. Compilers generated different ordering of names $1, $2 for anonymous classes, hence instance of $1 was sent by server but could not be received as $1 at client side. More info in blogpost (in Czech, though example is obvious).
Related videos on Youtube
Shekhar
Currently working as a Techno architect for AstraZeneca. Have vast experience of Big Data application design, planning, development, deployment and other phases of application development. Have hands on experience in Amazon Web Services, Hadoop, Hive, Pig, HBase, Kafka, IoT, Java, Storm technologies.
Comments
I am using SSA parser library in my project. When I invoke main method of one of it’s class using command prompt it works fine on my machine. I execute following command from command prompt :
java -Xmx800M -cp %1 edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTMPSubcategories -outputFormat "penn,typedDependenciesCollapsed" englishPCFG.ser.gz %2
But when I tried to use the same class in my java program, I am getting Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; edu.stanford.nlp.stats.Counter; class invalid for deserialization exception. Following line throws error :
LexicalizedParser _parser = new LexicalizedParser("C:\englishPCFG.ser.gz");
This englishPCFG.ser.gz file contains some classes or information which gets loaded when creating object of type LexicalizedParser . Following is the stacktrace :
Loading parser from serialized file C:\englishPCFG.ser.gz . Exception in thread "main" java.lang.RuntimeException: Invalid class in file: C:\englishPCFG.ser.gz at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromSerializedFile(LexicalizedParser.java:822) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromFile(LexicalizedParser.java:603) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.(LexicalizedParser.java:168) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.(LexicalizedParser.java:154) at com.tcs.srl.ssa.SSAInvoker.(SSAInvoker.java:21) at com.tcs.srl.ssa.SSAInvoker.main(SSAInvoker.java:53) Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; edu.stanford.nlp.stats.Counter; class invalid for deserialization at java.io.ObjectStreamClass.checkDeserialize(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.defaultReadFields(Unknown Source) at java.io.ObjectInputStream.readSerialData(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source) at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromSerializedFile(LexicalizedParser.java:814) . 5 more Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; class invalid for deserialization at java.io.ObjectStreamClass.initNonProxy(Unknown Source) at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) at java.io.ObjectInputStream.readClassDesc(Unknown Source) . 17 more
I am new to Java world so I dont to why this error is coming and what should I do to avoid it. I googled for this error then I found out that this error comes because of some version mismatch which I think is something similar to dll hell of windows API. Am I correct? Anyone knows why this kind of error comes? and what should we do to avoid it? Please enlighten .
thanks a lot for your input. Ill look into downloaded package if I can find compatible version of that class.
class invalid for deserialization
posted 12 years ago
I have the following code. Running in NetBeans. I’m receiving an error that «class invalid for deserialization»
What do I need to do here to prepare the class for deserialization?
Bartender
posted 12 years ago
Ernest Friedman-Hill wrote: That error message is generally only going to come up in weird situations in which a class implements the Serializable interface, objects of the class are serialized, the class is then modified to not implement Serializable, and then you try to deserialize the contents of the file.
author and iconoclast
posted 12 years ago
OK, that explains it, then! You saved a SaveBox in the file, and so Java is going to look for a class file named SaveBox to load when the file is read. But the SaveBox it finds when the class is read is not serializable, so this isn’t going to work! You need to do two things differently:
1) To load foo.ser, you need SaveBox.class to exist, and (most importantly!) it needs to be the same class that was saved into the file — i.e. the second one you showed me. Therefore, you’re going to have to name your file reading class something else!
2) Once you fix that problem, your program will still fail. That’s because you wrote a SaveBox, but you’re trying to read two Integers. You need to read a SaveBox instead. Whatever you write ot the file, that’s what you’re going to get back out. So.
Your SaveBox class doesn’t have getWidth and getHeight — you’ll need to add those.
help:class invalid for deserialization
posted 17 years ago
im using jboss server.im getting following exception while making call to session bean from my java client application:
the problem is generated only on my machine other guys dont get such problem.
also the transaction works fine the data is properly manupilated in database.but at the end this exception is thrown
in the folloiwing trace.ResulObject seems to be the root cause.this
class is used by bean developers to set the transaction success/failure details.
ShrtCdMgmtDAO.insertRec] : Record could not be created for some reasons
[ShrtCdMgmtDAO.insertRec] : Exception generated e—>java.lang.reflect.UndeclaredThrowableException java.lang.reflect.UndeclaredThrowableException
at $Proxy1.addShortCodeData(Unknown Source)
at ShrtCdMgmtDAO.insertRec(ShrtCdMgmtDAO.java:69)
at com.gomobile.cmdadminui.GMAdminUIShrtCdMst.readCommands(GMAdminUIShrtCdMst.java:154)
at GMAdminUIShrtCdMst.main(GMAdminUIShrtCdMst.java:379)
Caused by: java.io.InvalidClassException: ResultObject; class invalid for deserialization
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.rmi.MarshalledObject.get(Unknown Source)
at org.jboss.invocation.jrmp.interfaces.JRMPInvokerProxy.invoke(JRMPInvokerProxy.java:119)
at org.jboss.invocation.InvokerInterceptor.invokeInvoker(InvokerInterceptor.java:227)
at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:167)
at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:46)
at org.jboss.proxy.SecurityInterceptor.invoke(SecurityInterceptor.java:55)
at org.jboss.proxy.ejb.StatelessSessionInterceptor.invoke(StatelessSessionInterceptor.java:97)
at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:86)
. 4 more
[ March 26, 2006: Message edited by: jaspal singh ]
Teach me the art of forgetting, for I always remember wat I have forgotten.