Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `Class` class final?

Answering a question here at SO, I came up to a solution which would be nice if it would be possible extend the Class class:

This solution consisted on trying to decorate the Class class in order to allow only certain values to be contained, in this case, classes extending a concrete class C.

public class CextenderClass extends Class
{
    public CextenderClass (Class c) throws Exception
    {
        if(!C.class.isAssignableFrom(c)) //Check whether is `C` sub-class
            throw new Exception("The given class is not extending C");
        value = c;
    }

    private Class value;

    ... Here, methods delegation ...
}

I know this code does not work as Class is final and I wonder why Class is final. I understand it must have to do with security but I can't imagine a situation where extending Class is dangerous. Can you give some examples?

By the way, the closer solution for the desired behavior I can reach is:

public class CextenderClass
{
    public CextenderClass(Class c) throws Exception
    {
        if(!C.class.isAssignableFrom(c)) //Check whether is `C` sub-class
            throw new Exception("The given class is not extending C");
        value = c;
    }

    public Class getValue() {
        return value;
    }

    private Class value;

}

But it lacks the beauty of transparent decoration.

like image 260
Pablo Francisco Pérez Hidalgo Avatar asked Jul 28 '14 12:07

Pablo Francisco Pérez Hidalgo


1 Answers

According to comments in the Class class Only the Java Virtual Machine creates Class objects..

If you were allowed to extend classes, then a problem would arise, should you be allowed to create custom Class objects?. If yes, then it would break the above rule that only the JVM should create Class Objects. So, you are not given that flexibility.

PS : getClass() just returns the already created class object. It doesn't return a new class object.

like image 153
TheLostMind Avatar answered Oct 29 '22 17:10

TheLostMind