将Resource转为Collection<? extends Resource>时遇ClassCastException问题求助
Let's break down what's going on here and fix that error.
First, looking at your eSet implementation:
public void eSet(int featureID, Object newValue) { switch (featureID) { case LibraryPackage.RESOURCE_CONSUMER_A__REQUIRED_RESOURCES: getRequiredResources().clear(); getRequiredResources().addAll((Collection<? extends Resource>)newValue); return; case LibraryPackage.RESOURCE_CONSUMER_A__CONSUMED_GROUPS: getConsumedGroups().clear(); getConsumedGroups().addAll((Collection<? extends ResourceGroup>)newValue); return; } super.eSet(featureID, newValue); }
For those two specific featureIDs (REQUIRED_RESOURCES and CONSUMED_GROUPS), the code expects newValue to be a Collection (since it calls addAll on an existing collection). But in your call:
FatherObject.eSet(FatherObject.eClass().getEAllReferences().get(v), ContainedObject);
You're passing a single ContainedObject instead of a collection holding that object. That's exactly why you're hitting the ClassCastException—you can't cast a single ResourceConsumptionImpl instance to a Collection.
Fixes to Try
1. Wrap your single object in a collection (if the feature expects a collection)
If FatherObject.eClass().getEAllReferences().get(v) corresponds to either REQUIRED_RESOURCES or CONSUMED_GROUPS, wrap your ContainedObject in a collection before passing it to eSet. Use something like:
// Use Collections.singletonList for an immutable single-element collection Collection<Resource> wrappedObject = Collections.singletonList((Resource) ContainedObject); FatherObject.eSet(FatherObject.eClass().getEAllReferences().get(v), wrappedObject);
Or if you need a mutable collection:
ArrayList<Resource> wrappedObject = new ArrayList<>(); wrappedObject.add((Resource) ContainedObject); FatherObject.eSet(FatherObject.eClass().getEAllReferences().get(v), wrappedObject);
Make sure to cast ContainedObject to the correct type (like Resource or ResourceGroup) based on which feature you're targeting.
2. Verify you're using the correct feature ID
If you intended to set a single-value feature (not a collection), you might have picked the wrong index v in getEAllReferences(). Debug this by printing the name of the reference you're targeting:
EReference selectedRef = FatherObject.eClass().getEAllReferences().get(v); System.out.println("Targeted reference: " + selectedRef.getName());
Check if the printed name matches requiredResources or consumedGroups (which are collection types). If not, adjust the index v to point to the single-value reference you actually want.
内容的提问来源于stack exchange,提问作者George

