简体   繁体   中英

Cast type using an instance

The error: CAP#1 is not a fresh type

The code:

public Boolean isAssigned(HttpServletRequest request, String name, Foo foo) {
    Boolean isAssigned = false;

    if ((foo.getClass()) request.getSession().getAttribute(name) != null) {
        isAssigned = true;
    }

    return isAssigned;
}

What is the solution?

May not be what you are looking for but it answers the question in the title.

The Class<T> class has a cast method which can cast any object to its own type T . Obviously it will throw a ClassCastException if the object cannot be cast to that type.

public <T> T castTo(Class<T> t, Object o) {
    return t.cast(o);
}

public <T> T castTo(T t, Object o) {
    return (T) castTo(t.getClass(), o);
}

public void test() {
    String s = "Hello";
    Object b = s;
    String c = castTo(String.class, b);
    String d = castTo("Some String", b);
}

If you want to test whether

request.getSession().getAttribute(name)

is of type Foo and execute a method method on it afterwards you could simply try using instanceof and cast :

if (request.getSession().getAttribute(name) instanceof Foo) {
    ((Foo) request.getSession().getAttribute(name)).method();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM