How does a '.class' property work?

后端 未结 5 919
孤城傲影
孤城傲影 2020-12-06 09:54

First time developing in Java, and first time developing for Android, so it\'s quite a newbie question.

I currently have this code:

public void onBt         


        
相关标签:
5条回答
  • 2020-12-06 10:10

    The .class method is one all objets have which allow you to reference the original nature of that object from before you even had a chance to initialize it. It's not the parent, it's the original unadulterated template of itself. It's called ".class" because it's a direct representation of the class that only the class definition can influence. It saves you from having to make a new object in order to obtain information all members of that class originally have in common.

    0 讨论(0)
  • 2020-12-06 10:11

    Class is a class that represents classes. :)

    It is not "Object". It is not a superclass or even in your "NewTourny" hierarchy. That is why you can't cast from a NewTourney to a Class.

    The .class property is an instance of Class that represents type information.

    You can use it to do reflective style calls to instantiate something you don't know the type of at compile time.

    0 讨论(0)
  • 2020-12-06 10:13

    It doesn't really do much. NewTourney.class is more of a language specific way to write "the object which is the Class of NewTourney". This shorthand allows one to refer to the class of a NewTourney, as opposed to dealing with specific already existing instances of NewTourney.

    In your specific case, I would hazard to guess that the Activity eventually creates an instance of the class to handle the action, or at least to hold the action's context sensitive data.

    0 讨论(0)
  • 2020-12-06 10:24

    Instances of the class where Class represent classes and interfaces in a running Java application. This is part of java Reflection API. From Oracle tutorial:

    If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

    Here are some references:

    1. https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
    2. https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
    0 讨论(0)
  • 2020-12-06 10:35

    To get rid of the warning, you can change Class c with Class<? extends Tourny>. This means c is not an object, that represents one of all possible classes, but more specifically represents a class derived by Tourny.

    0 讨论(0)
提交回复
热议问题