Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Terminology

Tags:

java

I am new to Java and would like to know a bit more. I have a current problem that I would like an answer to, but I would also like to know what the technique is referred to as so that I can do some further reading.

I currently have something like this:

public class BasicActivityExtension {
    public Boolean basicExtensionMethod() { }
    ...
}

public class MyExtension extends BasicActivityExtension {
    public Boolean myExtensionMethod() { }
    ...
}

Then in a service method I have (ignore the ( I couldnt work out how to get the < to stay in this):

public Class < ? extends BasicActivityExtension> getExtensionByActivity(
                                                     BasicActivity activity,
                                                     ExtensionTypes type)
                                                 throws Exception {
    ...
}

My Question is why does this give an error and what is the name for this technique (when done correctly!)

MyExtension members = (MyExtension) activityService.getExtensionByActivity(activity,
                                        ExtensionTypes.member);

The error is Cannot cast from Class to MyExtension;

Also if I have an object Class< ? extends BasicActivityExtension> how can I just call the generic methods in BasicActivityExtension without caring what class it is?

like image 868
Rob Avatar asked Apr 28 '26 00:04

Rob


2 Answers

It appears you want

<T extends BasicActivityExtension>
public T getExtensionByActivity(BasicActivity activity, ExtensionTypes type) {
....
}

When you specify Class it has to be a class object, not an instance of a class.

BTW: I would avoid blindly throwing Exception There are better ways of handling checked exceptions.

like image 154
Peter Lawrey Avatar answered Apr 29 '26 14:04

Peter Lawrey


What you are doing is called casting.

The problem is occurring because you are returning an object of type Class from your method getExtensionByActivity. However, you are attempting to cast this to an object of type MyExtension. You would fix this problem by changing the return type of getExtensionByActivity from Class to MyExtension.

like image 43
Jack Edmonds Avatar answered Apr 29 '26 13:04

Jack Edmonds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!