标签: classcastexception

Java:未选中从X转换为Y /如何实现castOrNull

我已经实现了这个功能:

 static <X,Y> Y castOrNull(X obj) {
  try {
   return (Y)obj;
  }
  catch(ClassCastException e) {
   return null;
  }
 }
Run Code Online (Sandbox Code Playgroud)

这给了我编译器警告:

Type safety: Unchecked cast from X to Y
Run Code Online (Sandbox Code Playgroud)

我不太明白.这不是try/catch我在这里做的检查吗?我可以忽略这个警告吗?

我的功能是否会按预期工作?我该如何正确实现它?

我也试过obj instanceof Y检查,但由于Java处理泛型的方式,这不起作用.

顺便说一句,这个函数对我来说似乎非常有用(使其他代码更干净).我想知道Java中是否已存在这样的函数?


我想要使​​用它的一个例子:

    void removeEmptyRawStrings() {
        for(Iterator<Entity> e = entities.iterator(); e.hasNext();) {
            RawString s = castOrNull(e.next());
            if(s != null && s.content.isEmpty()) e.remove();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的代码中经常出现类似这样的情况.我认为这比其他任何东西都更具可读性和简单性.但是,如果你有任何关于如何使代码更简单的话,请给我一个更好的建议.

java casting instanceof classcastexception

6
推荐指数
1
解决办法
3918
查看次数

奇怪的classCastException hibernate 3.5 glassfish

嗨,我有一个问题,我无法自己解决.我有一个war文件打包在耳中并运行在glassfish 3.0.1上,hibernate 3.5作为JPA提供程序.我用maven编译它并用想法或手动部署它.每隔一次我在我的DAO中得到一个强制转换异常:

java.lang.ClassCastException: com.myproject.domain.entity.User cannot be cast to 
com.myproject.domain.entity.User
Run Code Online (Sandbox Code Playgroud)

其他时候它完美无缺.这种行为没有模式.有人可以对这里发生的事情有所了解吗?

在com.myproject.domain.dao.UserDAOImpl.checkUserSessionValid(UserDAOImpl.java:195)中抛出异常的示例方法

public User checkUserSessionValid(String sessionId) {
        User user = null;
        EntityManager em = provider.entityManager();

        try {
            em.getTransaction().begin();
           //Query q = em.createQuery("SELECT u FROM User u WHERE u.session.sessionId = :sessionId"); makes no difference :/
            Query q = em.createQuery("SELECT u FROM User u WHERE u.session.sessionId = :sessionId",User.class);
            q.setParameter("sessionId", sessionId);
            user = (User) q.getSingleResult();

            em.getTransaction().commit();
        } catch (NoResultException ignored) {

        } finally {
            em.close();
        }

        return user;
 }

My libraries
[INFO] +- …
Run Code Online (Sandbox Code Playgroud)

java hibernate jpa glassfish classcastexception

6
推荐指数
1
解决办法
3443
查看次数

由于ClassLoader问题导致ClassCastException的解决方案

我有两个ClassLoader加载相同的类.所以,显然这些不能相互投射.但是我需要访问在另一个ClassLoader中创建的对象.

我可以访问两个ClassLoader.如何在其他类中使用该对象?我不需要将对象转换为与当前ClassLoader匹配.

但问题是返回的对象的类型是Object.所以,我必须抛弃该对象来访问某些方法.我怎样才能做到这一点?像下面这样的正常转换会导致ClassCastException,我已经知道了.

Mojo mojo = (Mojo) descriptor.getMojo();
Run Code Online (Sandbox Code Playgroud)

descriptor#getMojo()返回一个类型的对象,Mojo但该方法返回Object.怎么办呢?

如果您需要进一步的信息,请告诉我.

我已经阅读了有关类加载的所有理论,但没有一个为此指定了适当的解决方案.

java classloader classcastexception

6
推荐指数
1
解决办法
2万
查看次数

Hibernate java.lang.ClassCastException:org.hibernate.action.EntityIdentityInsertAction无法强制转换为org.hibernate.action.EntityInsertAction

我正在使用Hibernate和EntityManager.我用的时候

    Session session = (Session)entityManager.getDelegate();  
    session.flush();
    session.clear();
Run Code Online (Sandbox Code Playgroud)

我明白了

java.lang.ClassCastException: org.hibernate.action.EntityIdentityInsertAction cannot be cast to org.hibernate.action.EntityInsertAction
at org.hibernate.engine.ActionQueue$InsertActionSorter.sort(ActionQueue.java:636)
at org.hibernate.engine.ActionQueue.sortInsertActions(ActionQueue.java:369)
at org.hibernate.engine.ActionQueue.sortActions(ActionQueue.java:355)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:224)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
Run Code Online (Sandbox Code Playgroud)

既然它没有说明哪个实体导致问题,我就被困在这里.有谁知道是什么原因引起的?

hibernate flush entitymanager classcastexception

6
推荐指数
1
解决办法
2168
查看次数

findViewById上的android ClassCastException

我有一个小问题,我找不到我正在犯的错误,这可能是非常简单的事情.

我有以下布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp" >

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false" />
    <ImageView
        android:id="@+id/imgStarred"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/checkBox"
        android:layout_below="@+id/checkBox"
        android:layout_marginRight="4dp"
        android:src="@drawable/ic_star_gray"/>


    <CheckedTextView
        android:id="@+id/lblTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/checkBox"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="8dp"
        android:layout_toLeftOf="@+id/imgPriority"
        android:layout_toRightOf="@+id/checkBox"
        android:text="CheckedTextView" />

    <TextView
        android:id="@+id/lblDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/lblTitle"
        android:layout_below="@+id/lblTitle"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/checkBox"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <ImageView
        android:id="@+id/imgPriority"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/ic_priority_5" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

当我尝试使用findViewById从中获取视图时,我得到了ClassCast异常

11-23 10:12:07.680: E/AndroidRuntime(5965): FATAL EXCEPTION: main
11-23 10:12:07.680: E/AndroidRuntime(5965): java.lang.ClassCastException: android.widget.ImageView
11-23 10:12:07.680: E/AndroidRuntime(5965):     at com.bilobait.taskbox.task.TaskBoxTaskList$TaskView.<init>(TaskBoxTaskList.java:459)
11-23 10:12:07.680: E/AndroidRuntime(5965): …
Run Code Online (Sandbox Code Playgroud)

layout android classcastexception

6
推荐指数
1
解决办法
4764
查看次数

附加对象OutputStream时的ClassCastException

我一直在尝试做一个需要可附加的ObjectOutputStream的小项目.我已经经历了几个解决方案,我发现这一点似乎首先解决了我的问题.但是在我的项目的进一步发展中,我开始遇到意外的异常.以下是我的课程.

public class PPAccount implements Serializable
{
    private Profile profile;
    private String email;
    private float accountBal;
    private boolean isActivated;
    private String activationCode;
    private ArrayList<Transaction> transactions;

    //a few functions   
}
public class PPRestrictedAccount extends PPAccount {
    private String parentEmail;
    private float withdrawLimit;

        //a few functions
}
public class PPBusinessAccount extends PPAccount {
    private ArrayList <PPRestrictedAccount> accountOperators;

        //a few functions
}
public class PPStudentAccount extends PPAccount {
    private String parentEmail;

        //a few functions
}
Run Code Online (Sandbox Code Playgroud)

我观察到的是,使用这个我已经覆盖了ObjectOutputStream并在我将对象附加到文件时使用它.但是如果我写的话会发生什么:

PPBusinessAccount首先,重复任意次数...然后写PPAccount …

java serialization classcastexception java-io

6
推荐指数
1
解决办法
8812
查看次数

使用android.support.v7.widget.SearchView时获取类转换异常

我正在使用菜单在操作栏上显示"搜索"图标.我已经创建了搜索视图

itemSearch = menu.findItem(R.id.action_search_chat_home_container);
searchView = (SearchView) MenuItemCompat.getActionView(itemSearch);
Run Code Online (Sandbox Code Playgroud)

我使用android-support-v7-appcompat作为库项目.

菜单XML ...

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:homecontainer="http://schemas.android.com/apk/res-auto" >

  <item
    android:id="@+id/action_search_chat_home_container"
    android:icon="@drawable/ic_action_search"
    android:title="@string/action_search"
    homecontainer:showAsAction="ifRoom|collapseActionView"
    homecontainer:actionViewClass="android.support.v7.widget.SearchView"/>

</menu>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

*03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993): java.lang.ClassCastException: android.support.v7.internal.view.menu.MenuItemWrapperICS$CollapsibleActionViewWrapper cannot be cast to android.support.v7.widget.SearchView
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at com.abc.contactbook.RTContactBookActivity.onCreateOptionsMenu(RTContactBookActivity.java:874)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1560)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1949)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1563)
03-18 12:19:46.965 E/com.rancore.contactbook.RTContactBookActivity<======(14993):   at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1949)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:224)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:141)
03-18 12:19:46.965 E/com.abc.contactbook.RTContactBookActivity<======(14993):   at …
Run Code Online (Sandbox Code Playgroud)

java android classcastexception android-fragments searchview

6
推荐指数
1
解决办法
4471
查看次数

JDK8 类型推断问题

由于类型推断,我正在尝试运行以下代码,这些代码在 JDK8 下编译得很好:

public static <A,B> B convert(A a) {
  return (B) new CB();
}
public static void main(String[] args) {
  CA a = new CA();
  CB b = convert(a); //this runs fine
  List<CB> bl = Arrays.asList(b); //this also runs fine
  List<CB> bl1 = Arrays.asList(convert(a)); //ClassCastException here
}
Run Code Online (Sandbox Code Playgroud)

但是,运行它会抛出 ClassCastException: CB cannot be cast to [Ljava.lang.Object,但 CB b = convert(a) 工作正常。

知道为什么吗?

type-inference javac classcastexception java-8

6
推荐指数
1
解决办法
127
查看次数

java.lang.RuntimeException:无法在 Flutter 中实例化活动

Flutter 新创建的应用程序在使用 fire base 时出错。

我应该如何解决这个问题,因为它要求 Flutter 应用程序主活动无法转换为 android 应用程序活动。

04-05 21:16:07.570 27391-27391/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.firestoreflutterchat, PID: 27391
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firestoreflutterchat/com.example.firestoreflutterchat.MainActivity}: java.lang.ClassCastException: com.example.firestoreflutterchat.MainActivity cannot be cast to android.app.Activity
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2124)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
        at android.app.ActivityThread.access$800(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5097)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.example.firestoreflutterchat.MainActivity cannot be cast to android.app.Activity
        at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2115)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257) 
        at android.app.ActivityThread.access$800(ActivityThread.java:139) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) 
        at …
Run Code Online (Sandbox Code Playgroud)

classcastexception firebase flutter android-module

6
推荐指数
3
解决办法
7134
查看次数

ClassCastException 与 Stacktrace Hazelcast 版本 4.2.5 使用 ReplicatedMap

在部署在 Kubernetes 上 Tomcat 上的 Web 应用程序中使用 Hazelcast 版本 4.2.5。我们经常(“每 5 秒”)在应用程序日志中看到带有堆栈跟踪的 ClassCastException。

这是 ClassCastException :

java.lang.ClassCastException: class java.lang.String cannot be cast to class com.hazelcast.internal.serialization.impl.HeapData (java.lang.String is in module java.base of loader 'bootstrap'; com.hazelcast.internal.serialization.impl.HeapData is in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @2f04993d)
27-Oct-2022 22:57:56.357 WARNING [hz.rogueUsers.cached.thread-2] com.hazelcast.internal.metrics.impl.MetricsCollectionCycle.null Collecting metrics from source com.hazelcast.replicatedmap.impl.ReplicatedMapService failed
        at com.hazelcast.internal.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:102)
        at com.hazelcast.internal.util.executor.HazelcastManagedThread.executeRun(HazelcastManagedThread.java:76)
        at java.base/java.lang.Thread.run(Thread.java:834)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at com.hazelcast.internal.util.executor.CachedExecutorServiceDelegate$Worker.run(CachedExecutorServiceDelegate.java:217)
        at com.hazelcast.spi.impl.executionservice.impl.DelegateAndSkipOnConcurrentExecutionDecorator$DelegateDecorator.run(DelegateAndSkipOnConcurrentExecutionDecorator.java:77)
        at com.hazelcast.internal.metrics.impl.MetricsService.collectMetrics(MetricsService.java:154)
        at com.hazelcast.internal.metrics.impl.MetricsService.collectMetrics(MetricsService.java:160)
        at com.hazelcast.internal.metrics.impl.MetricsRegistryImpl.collect(MetricsRegistryImpl.java:316)
        at com.hazelcast.internal.metrics.impl.MetricsCollectionCycle.collectDynamicMetrics(MetricsCollectionCycle.java:88)
        at com.hazelcast.replicatedmap.impl.ReplicatedMapService.provideDynamicMetrics(ReplicatedMapService.java:387)
        at com.hazelcast.replicatedmap.impl.ReplicatedMapService.getStats(ReplicatedMapService.java:357)
        at …
Run Code Online (Sandbox Code Playgroud)

java exception classcastexception hazelcast

6
推荐指数
1
解决办法
401
查看次数