logo
Tags down

shadow

ClassCastException in Inheritance - Why?


By : Pedro Adelino
Date : September 15 2020, 11:00 AM
like below fixes the issue The compiler infers the type returned by al.makeParent() according to the a() method being chosen by the method overloading resolution.
Since the method overloading resolution first considers candidates that don't have vararg arguments, only the public void a(List ss) overload is considered, and therefore that's the chosen overload.
code :
class Child extends Parent implements List<ParentI>


Share : facebook icon twitter icon

JPA Inheritance entitymanager.find produces ClassCastException


By : user2237852
Date : March 29 2020, 07:55 AM
To fix this issue I know that this has been a problem in Hibernate during a long time, see for example:
ClassCastException cglib lazy loading JPA: instanceof vs. hibernate proxy: when is it safe? How to Avoid ClassCastExceptions when using Hibernate Proxied Objects)
code :
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-cglib-repack</artifactId>
        <version>2.1_3</version>
    </dependency>
    <dependency>
      <groupId>javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.8.0.GA</version>
    </dependency>
<project>
  ...
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.10</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
  ...
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>3.4.0.GA</version>
      <exclusions>
        <exclusion>
          <groupId>javassist</groupId>
          <artifactId>javassist</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-cglib-repack</artifactId>
      <version>2.1_3</version>
    </dependency>
    ...
  </dependencies>
</project>
[INFO] +- org.hibernate:hibernate-entitymanager:jar:3.4.0.GA:compile
[INFO] |  +- org.hibernate:ejb3-persistence:jar:1.0.2.GA:compile
[INFO] |  +- org.hibernate:hibernate-commons-annotations:jar:3.1.0.GA:compile
[INFO] |  +- org.hibernate:hibernate-annotations:jar:3.4.0.GA:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:3.3.0.SP1:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.6:compile
[INFO] |  |  \- commons-collections:commons-collections:jar:3.1:compile
[INFO] |  +- org.slf4j:slf4j-api:jar:1.5.10:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  \- javax.transaction:jta:jar:1.1:compile
...
[INFO] \- org.hibernate:hibernate-cglib-repack:jar:2.1_3:compile

Java inheritance downcast ClassCastException


By : Hadi Valipour
Date : March 29 2020, 07:55 AM
To fix this issue All B's are A's, by inheritance. But not all A's are B's. This particular instance isn't, hence the runtime exception.

ClassCastException Object Inheritance with Retrofit


By : Polngpole Tharmmakol
Date : March 29 2020, 07:55 AM
This might help you Yes, the issue is the gson always creates the type in the retrofit call. You need to provide a custom deserializer to figure out the object type based on your type field. Here is a sketch of what that might look like.
code :
public class ModiaPojoDeserializer implements JsonDeserializer<Model> {

    private static final String TYPE_FIELD = "type";
    private static final String IMAGE_TYPE = "image";
    private static final String VIDEO_TYPE = "video";

    @Override
    public Model deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonObject() && json.getAsJsonObject().has(TYPE_FIELD)) {
            JsonObject jsonObject = json.getAsJsonObject();
            final String type = jsonObject.get(TYPE_FIELD).getAsString();
            if (VIDEO_TYPE.equals(type)) {
                return context.deserialize(json, VideoPojo.class);
            } else if (IMAGE_TYPE.equals(type)) {
                return context.deserialize(json, ImagePojo.class);
            } // ...
            // If you need to deserialize as MediaPojo,
            // deserialize without the current context 
            // or you will infinite loop
            return new Gson().fromJson(json, typeOfT);

        } else {
            // Return a blank object on error, could use null
            return new MediaPojo();
        }
    }
}
 Gson gson = new GsonBuilder()
     .registerTypeAdapter(MediaPojo.class, new MediaPojoDeserializer())
     .create();
RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.mydomain.com")
    .setConverter(new GsonConverter(gson))
    .build();

ClassCastException when intercept Parcelable with inheritance


By : Abeeha Aamir
Date : March 29 2020, 07:55 AM
I wish this help you Consider the following scenario(using the same classes, a is super, b is child):
You can do:
code :
A a = new B();
B b = new A();
B b = new A()

ClassCastException with Gson and class inheritance from generic ArrayList


By : fhatfiel
Date : March 29 2020, 07:55 AM
Hope that helps OK, I have just written a custom adapter and it works fine. It's going to be a bit more complicated with the real code, though, but at least I know who to solve this.
Here's the code:
code :
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

class IntegerArrayList extends ArrayList<Integer> {
    String customField = "test";

    public IntegerArrayList(Integer... items) {
        super();
        addAll(Arrays.asList(items));
    }

    public static IntegerArrayList fromJson(String json) {
        IntegerArrayList integerArrayList = new GsonBuilder()
                .registerTypeAdapter(IntegerArrayList.class, new JsonAdapter())
                .enableComplexMapKeySerialization()
                .create()
                .fromJson(json, IntegerArrayList.class);
        return integerArrayList;
    }

    public String toJson() {
        return new GsonBuilder()
                .registerTypeAdapter(IntegerArrayList.class, new JsonAdapter())
                .enableComplexMapKeySerialization()
                .setPrettyPrinting()
                .create()
                .toJson(this, IntegerArrayList.class);
    }

    public static class JsonAdapter extends TypeAdapter<IntegerArrayList> {
        @Override
        public void write(JsonWriter out, IntegerArrayList value) throws IOException {
            out.beginObject();
            out.name("customField").value(value.customField);
            out.name("items");
            out.beginArray();
            for (Integer v : value) {
                out.value(v);
            }
            out.endArray();
            out.endObject();
        }

        @Override
        public IntegerArrayList read(JsonReader in) throws IOException {
            IntegerArrayList rtn = new IntegerArrayList();
            in.beginObject();
            while (in.hasNext()) {
                switch (in.nextName()) {
                    case "customField":
                        rtn.customField = in.nextString();
                        break;
                    case "items":
                        in.beginArray();
                        while (in.hasNext()) {
                            rtn.add(in.nextInt());
                        }
                        in.endArray();
                }
            }
            in.endObject();
            return rtn;
        }
    }
}

public class GsonTest {
    public static void main(String[] args) {
        IntegerArrayList integerArrayList = new IntegerArrayList(1, 2, 3, 4, 5);
        String json = integerArrayList.toJson();
        IntegerArrayList integerArrayList1 = IntegerArrayList.fromJson(json);
    }
}
Related Posts Related Posts :
  • Junit Mockito mock not working as expected
  • Cannot Compile Java project
  • Java MIDI sequencer never ends
  • Java Spring: getting the generic type
  • copy specific elements if condition is met
  • How to parse time from string?
  • After upgrading spring version getting java.lang.NoClassDefFoundError:
  • How to close application on onBackPressed() in home activity
  • NullPointerException while setting field in Test Class
  • Order of serialization in Java
  • Vaadin 14 Grid + Dialog: How to refresh grid after closing dialog?
  • finding words within String and returning as String + spaces Java
  • Negative Values when calculating time of a java date
  • when case switch between kernel mode and user mode for synchronized keyword in JAVA
  • Creating a repetitive action in a GUI without 'time drift'
  • Why Map api doesn't provide stream capabilities in Java?
  • Multi threaded issue with myMethod()
  • Is Java Synchronization required when loading data from another thread once?
  • Pass Multiple Keys in @Requestparam with a Single String Variable
  • PriorityQueue returning elements in wrong order
  • How to get sum of doubles in list using stream?
  • How to remove field from object conditionally, by other ENUM field value
  • MariaDB and flyway syntax error but not in JAVA
  • How to check in an array list if an item is immediately followed by another - Java
  • Class FIle has no arguments at the constructor
  • JavaFx 13 - TableView Vertical ScrollBar handler returns NullPointerException
  • Code crashes every time the helper class is executed
  • Java Problem- Null char prints no character on Mac OS but does print a blank space on Windows
  • Configuration of a Spring Data Repository class to hit read_replica_db for read/select methods and main_db for write/ins
  • Java PriorityQueue poll() order of values
  • Intiize the Custom object with empty string in java
  • Facing issue to handle more then two window with selenium webdriver
  • How to set connectTimeout in case of slow internet and if I don't know the size of file to download
  • Regular expression to remove the dot (.) from a number
  • Access shared folder from linux machine using java code
  • java code style: returning specific Map implementation when generic contract is not sufficient
  • Java function inside __groovy executes but the result is not being assigned to a variable
  • Decorating a concrete class, bad practice?
  • Copy table from Oracle to Redis
  • Moshi Multiple Custom Names
  • Create actual date in string format from microseconds with precision of microseconds
  • How to generate a spinner in Android with different background color in each item with Java?
  • Java8 variable in for loop
  • Why is my java code throwing an error when I get input from the user?
  • Why does Java's Stream.reduce method take an identity element instead of a default result?
  • Upload arraylist using httpurlconnection multipart/form-data
  • Java split() method can not distinguish "." and "-" on Windows
  • Java HashMap Did Not Return Expected Result when put the data
  • I am doing an attendence program with java and mySQL, and its not working well with me. Here's the code:
  • IBM MQ JMS java listener code keeping the program running
  • Java 'finally' clause in a nested 'try' block
  • How to call methods in functional interfaces without .Method()
  • how to make list of duplicates in custom arraylist Java
  • Safe publication of array/collection/map contents written once
  • How to set a new value (Date) for a Java bean property?
  • ExecutorService thread safety
  • StringBuilder - setLength(0) vs new instantiate, what is better?
  • Upgraded spring boot from 2.1.0 to 2.2.2.RELEASE , now getting exception while starting
  • Is it possible to find the original sequence of integers from its prefix sums and suffix sums?
  • How can I round up to 3 Decimal places in Java such that .000 shoould be there at the end of the value even if it is a s
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk