ClassCastException errors are often encountered in Java programming , and the classcastexception is a runtime exception that is thrown when the JVM detects a conversion incompatibility between two types. This type of error usually terminates the user request. This model attempts to provide you with some basic elements to understand and exclude the most common causes of classcastexception errors.
Why does this issue occur?
ClassCastException can occur within application code or WebLogic Server code that performs almost any subsystem (Web container, EJB, JCA, cluster, and so on). By converting, you can instruct the Java compiler to handle variables of a given type as another variable. Both the underlying type and the user-defined type can be converted. The Java language specification defines the allowable transformations, most of which can be validated at compile time. However, some conversions also require run-time validation. If incompatibilities are detected during this run-time validation, the JVM raises classcastexception.
Suppose you have an object of type S, and we want to convert it to type T.
s S;
...
T t = (t) s;
The above conversions can cause classcastexception if any of the following conditions are true
S is incompatible with T. Specification: "When an application code attempts to convert an object to a subclass, the JVM throws ClassCastException if the object is not an instance of that subclass." "The following is a sample code that will throw such an error when executing the code:
public class Testcce {public static void main (String args[]) {
Object obj = new Object ();
string s = (string) obj;
}
}
The S type is compatible with the T type, but it is loaded with a different ClassLoader.
The second reason is actually the most common cause of this error. This situation is quite difficult to diagnose and requires some understanding of the basics of Java class loading and the WebLogic class loading architecture.
Back to top what is ClassLoader?
ClassLoader is a Java class that allows the JVM to find and load classes. The JVM has built-in ClassLoader. However, applications can define custom ClassLoader. Application-defined new ClassLoader typically have two main purposes:
Customize and extend the way the JVM loads classes. Example: Increased support for new class libraries (network, encrypted files, and so on)
Partition the JVM namespace to avoid name collisions. For example, a partitioning technique can be used to run multiple versions of the same application simultaneously (space-based partitioning). Another important use of this technology within an application server, such as WebLogic server, is to enable application hot-redeployment, which is to launch the new version of the application without restarting the JVM (based on time division).
ClassLoader are organized hierarchically. In addition to the system Boot ClassLoader, all other ClassLoader must have a parent ClassLoader.
Understand the key to class loading
Keep in mind that the following will help:
Classes can never be reloaded in the same ClassLoader: Hot redeploy requires the use of a new ClassLoader. Each class's reference to its ClassLoader is immutable: This.getclass (). getClassLoader ()
Before the class is loaded, ClassLoader always asks its parent ClassLoader (the delegate model) first. This means that you will never be able to override the "core" class
Peer ClassLoader between the non-understanding
The same class of files loaded by different ClassLoader are also considered different classes, even if each byte is identical. This is a typical cause of classcastexception.
You can use Thread.setcontextclassloader (CL) to connect ClassLoader to the context of a thread
Diagnosis
You can usually get a full classcastexception stack trace on the server's logs and/or clients. This stack should allow you to have a good understanding of the situation in the WebLogic Server subsystem involved. Use this information to verify that the problem is consistent with a known WebLogic Server issue. If so, please use the appropriate workaround.
If the error does not match the situation of all known issues, further probing is required. If the error is present in the class where you can edit and compile the source code, the following methods may help you understand the problem.
Suppose the line of code where the error occurred is similar to:
oo f = (Foo) bar.method ();
If the transformation should be valid according to the conversion rules, but still raises the classcastexception, it is possible that the class "bar" and "Foo" are loaded by different ClassLoader. To verify this, split the line of code as follows:
Object o = Bar.method ();
System.err.println ("the object" + O + "ClassLoader is" +
O.getclass (). getClassLoader ());
System.err.println ("Class Foo class loader is" +
Foo.class.getClassLoader ());
Foo f = (foo) o;
A typical output might look like this:
The object [email protected]@3e86d0 classloader is
[Email protected]
Class Foo ClassLoader is
[Email protected] Finder:
[Email protected]
The next step is to explore why different ClassLoader are involved. Please perform the checks in the following checklist:
Check the application packaging and check if "Foo" is packaged with different modules loaded by different ClassLoader. A known cause in this regard is the "prefer-web-inf-classes" feature of WEB applications (see known WebLogic issues)
Check the application code that it is using or whether a framework code has changed the context ClassLoader of the WebLogic thread and did not restore it during the request process. This can occur if there is a call to Thread.setcontextclassloader (CL) within the application code.
If all of these measures don't help, try isolating the issue in a simple, reproducible test case, and then contact BEA Technical support for further exploration. Known WebLogic Server issues The following is a collection of scenarios that can cause classcastexception errors that you might encounter when using various WebLogic subsystems. Small program
Summary: If the WebLogic Server client in the applet tries to obtain some resource information from ClassLoader and uses both the cache flag and the codebase=/bea_wls_internal/classes flag, it may throw ClassCastException.
Workaround:
Do not use caching options such as "Cache_option" and "cache_archive" when using a classpath servlet as a code base.
When using the caching option, do not use/classes (Classpathservlet) as the code base. If you want to do this, first use the Archive utility to package the client JAR. Can refer to the major it online education platform.
Summary: When a connection request is made, WebLogic Server returns a proxy object that is encapsulated by the resource adapter and returned to the client. WebLogic server uses this proxy to provide functionality to help applications use the WebLogic Server's "Java EE Connector Architecture" implementation. These features include the (1) connection leak detection feature and (2) a connection request that delays XAResource enlistment when it is issued before starting a global transaction that uses the connection.
ClassCastException can occur if the connection object returned by the connection request is converted to the original Connection class. The object that caused the exception is only during the connection request: (1) When the resource adapter is transitioning or (2) the client is converting.
In WebLogic Server 8.1 SP2, an attempt was made to detect classcastexception caused by the above resource adapter condition (1). If the server detects that the conversion failed, the agent wrapper feature is turned off and the connection object is returned (not wrapped) during the connection request. The server logs a warning message stating that the agent wrapper has been closed. In the event of such a conversion failure, the connection leak detection and XAResource deferred enlistment feature will also be turned off (but no indication is currently given in console monitoring).
WebLogic Server attempts to use container-managed security for client identity detection classcastexception. If you do this, the deployed resource adapter must define security credential.
If classcastexception occurs when the client performs the conversion, the client (client) code can be modified as follows:
WORKAROUND: If the client converts the connection object to MyConnection instead of MyConnection as a class that implements the Connection interface of the resource adapter, modify the object to an extended Connection interface. Implements a Myconnectionimpl class for implementing the MyConnection interface. Refer to the Wheat Academy for details.
Servlet Dynamic Reload
Summary: Objects stored in a servlet or Jsp,servlet session to be dynamically reloaded during a session must be serializable. Serialization is required because the servlet is reloaded with the new ClassLoader, which results in all classes previously loaded (classes in the old version of the servlet) and all classes loaded with the new ClassLoader (the new version of the Servlet class) An incompatible condition occurs. This incompatibility causes the servlet to return a classcastexception error.
Using the Prefer-web-inf-classes feature
Summary: The Weblogic.xml WEB application Deployment descriptor contains a prefer-web-inf-classes element (a child element of the Container-descriptor element). By default, this element is set to False. If this element is set to True, the ClassLoader delegate model is not followed so that the load order of class definitions in the Web application takes precedence over class definitions in the higher-level ClassLoader. This allows the WEB application to use its own version of the third-party class, which may also be part of the WebLogic Server. See Weblogic.xml Deployment
Descriptor Elements (中文版).
When you use this feature, you must be careful not to confuse instances created with a class definition that uses a WEB application with an instance created using the server's definition. If such instances are confused, classcastexception occurs.
Cluster: Store a custom object containing Ejbobject in an HTTP session? CR102119
Summary: A serializable custom object wraps Ejbobject (a reference to an EJB). The custom object is stored in an HTTP session. This design causes classcastexception when a session is copied.
Workaround: This issue will be completely resolved in a later version of WebLogic Server. The current workaround is to store the EJB handle (not ejbobject) within the wrapper. Cluster: Failover using EJB handles in an HTTP session? CR187062
Summary: Deploy WEBAPP and EJBS separately in the cluster.
The EJB handle is wrapped in a serializable custom object, and the object is stored in an HTTP session. Failover, the classcastexception occurs when the EJB is accessed through a handle.
Workaround: Wrap webApp and EJBs in the same ear file. The problem exists in WLS 8.1SP2 and is currently awaiting correction.
Wheat Academy Android Development Java Tutorial classcastexception error parsing