Reputation: 51
I am writing a URL validator. The code is as follows
public ValidationResult validate(final Object data, final Object root, final String path, final ValidationContext validationContext, final EvaluationContext evaluationContext) {
ValidationResult validationResult = new ValidationResult();
@SuppressWarnings("unchecked")
List<URL> URLs = (List<URL>)data;
UrlValidator urlValidator = new UrlValidator();
boolean isValid = true;
for (URL websiteURL : URLs) {
if (urlValidator.isValid(websiteURL.getPath())) {
isValid = true;
} else {
isValid = false;
break;
}
System.out.println("websiteURL.getPath() " + websiteURL.getPath());
}
System.out.println("websiteURL.getPath() " + isValid);
return validationResult;
}
While debugging i found that for (URL websiteURL : URLs)
is giving java.lang.ClassCastException: java.net.URI cannot be cast to java.net.URL
error. How can i make my logic work?
Upvotes: 2
Views: 3194
Reputation: 719346
The real problem is here:
@SuppressWarnings("unchecked")
List<URL> URLs = (List<URL>)data;
In fact, it would appear that you are calling this code with an object that is a list of URI
objects rather than a list of URL
objects. At any rate, the class cast is happening in a hidden cast that happens when the object returned by the Iterator.next()
object is assigned to websiteURL
.
It is not really clear what the correct solution to this is:
You could (possibly) change the code that calls this to pass it a list containing URL
objects ... as expected by the validator.
You could change the validator to work on a list of URI
objects ... starting with the declaration of the URLs
variable. (YUCK! Didn't anyone explain Java identifier conventions to you??)
@SuppressWarnings("unchecked")
List<URI> uris = (List<URI>)data;
You could change the validator to work with URL
and URI
objects ... starting by changing the above declaration to:
List<?> urls = (List) data;
Then you need to use instanceof
to discriminate between URI
and URL
objects before validating them.
For the record, the way to convert a URI
to a URL
is to call URI.toURL()
on it.
Upvotes: 1