-2

I am trying to make an checkFalse method where i take Object as an argument. I now want to check if that Object is the same type as this.getClass(). If it is of the same type, i now want to cast the Object to that class in order to access the methods of that object class!

For example, how can i access the SomeMethod from that f object? I am trying to convert the object F to the class testMain.

Error: Cannot be cast to testMain

class testMain implements testest
{

}

interface testest
{
    public default boolean SomeMethod()
    {

    }

    public default boolean checkFalse(Object f) throws  ClassCastException
    {
        try 
        {
            f = this.getClass();
        } 
        catch (ClassCastException exception) 
        {
            throw exception;
        }
        f = (testMain)f; //Here. How do i turn this object to the    class testMain so that i can access that objects methods? For example, how can i access the SomeMethod through this f object?
     }
}
6
  • I've removed the c# code since this is clearly a Java question. Commented Feb 10, 2019 at 11:15
  • Okay sure. Included c# because they are almost identical. But fair enough! Commented Feb 10, 2019 at 11:16
  • You have to cast to testest (not testMain). By the way: Stick to the Java code conventions, and write class and interface names in CamelCase. Commented Feb 10, 2019 at 11:17
  • I tried that but i get the same error only now it says "Cannot be cast to testtest" Commented Feb 10, 2019 at 11:19
  • Casting to testest gives you the error "cannot be cast to Queue" ??? Commented Feb 10, 2019 at 11:20

1 Answer 1

0
public default boolean checkFalse(Object f) {
    if(f instanceof testest) {
        ((testest)f).someMethod();
    } else
        throw new RuntimeException();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.