As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.
package com.main.service;
public interface SomeService{
public void someMethod();
}
But why below code is allowed in Java?
com.main.service.SomeService.class;
I am using this code to get beans from Spring application context like below:-
SomeService someservice = applicationContext
.getBean(com.main.service.SomeService.class);
The .class syntax at the end of a type (com.main.service.SomeService.class; in this case) references the class literal, which is an object of type Class. You can use this on any Java type, be it a concrete class, abstract class or an interface.
As per the Javadoc from the link above:
Instances of the class Class represent classes and interfaces in a running Java application
This may be confusing if you're new, and are used to having the distinction between class and interface drummed into you, but simply speaking it's how the underlying system works (all classes and interfaces are compiled to bytecode class files.)
You commonly see the syntax used in dependency injection (or other uses where you need to pass the "type" of something around), as it's the easiest way of doing so.
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
ClassLiteral:
TypeName {[ ]} . class
NumericType {[ ]} . class
boolean {[ ]} . class
void . class
The type of C.class, where C is the name of a class, interface, or
array type, is Class.
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
You should look at the Java docs of the method that you are using:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.Class-
Importantly the javadoc states:
Return the bean instance that uniquely matches the given object type,
if any.
NoUniqueBeanDefinitionException - if more than one bean of the given
type was found
So if you have more that one beans extending the interface you will get exception.
Related
There are 2 ways to get a class's Class object.
Statically:
Class cls = Object.class;
From an instance:
Object ob = new Object();
Class cls = ob.getClass();
Now my question is getClass() is a method present in the Object class,
but what is .class? Is it a variable? If so then where is it defined in Java?
That's implemented internally and called a class literal which is handled by the JVM.
The Java Language Specification specifically mentions the term "token" for it.
So .class is more than a variable, to be frank it is not a variable at all. At a broader level you can consider it as a keyword or token.
https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.8.2
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader (§12.2) of the class of the current instance.
That information resides in the class 'file', although classes need not have a physical .class file in the file system. The JVM takes care of making it available from the class definition, as the other answer states.
See also:
https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html
I'd like to retrieve the actual class of the generic type that is found on an object's parametrized marker interface. Is this even possible?
The marker interface:
public interface MarkerInterface<T> {}
The method i'd like to have:
public class findClassForParametrizedMarkerInterface(MarkerInterface<T> markedObjectThatCouldExtendSomeRandomClass){
//How to retrieve the class T, or it's name?
}
For those wishing to know why I would like to do this:
I have multiple dto jpa entities for some heavy jpa entities. I'd like to create a generic service that retrieves the correct full entity spring data jpa repository for the supplied dto. The dto's have a marker interface that specifies as parametrized generic type the full entity class.
Edit: a good discussion can be found at Get generic type of class at runtime. The simplest solution is to pass a reference to the class at the time of instantiation of the object. Maintain a reference to this class to return when needed. This is due to Java not holding onto generics at runtime. The generic info is available in metadata if you want to use the verbose reflection api to retrieve it.
use getClass() on the object itself.
public final Class getClass()
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
The actual result type is Class where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:
Number n = 0;
Class c = n.getClass();
Returns:
The Class object that represents the runtime class of this object.
See Also:
Literals, section 15.8.2 of The Java™ Language Specification.
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass()
Is an interface a special kind of class or can you say that an interface isn't a class at all?
An interface isn't a class, but you could say that both interfaces and classes are types.
From the Java specification:
In the Java programming language, every variable and every expression has a type that can be determined at compile-time. The type may be a primitive type or a reference type. Reference types include class types and interface types.
Notice though there is a special class called Class<T> that can represent both classes and interfaces:
Instances of the class Class represent classes and interfaces in a running Java application.
The fact that an interface is represented by a Class instance where isInterface is true could give you the impression that an interface is just a special type of class. However this is not the case.
No, an interface is not a class in Java.
An interface is a type and all reference types (i.e. non-primitive types) handle quite similarly in Java. Often when people say "class" they are actually referring to a "reference type".
What might be confusing you is that an interface definition is stored in a .class file, but that's just a technical artifact of Java. In fact all reference type definitions (classes, interfaces, annotations, enums) are stored in .class files in Java.
The concept of interfaces comes from Abstract Classes, where as abstract classes contains prototypes of method (or abstract methods) and can have few of its methods defined also, while interfaces contains only the prototypes(or signature) of method or abstract methods, whose definition is to be provided by the implementing class.
so from the above statement it is clear that interfaces are like 100 percent abstract classes where -
none of its method is defined.
mentioning it again interfaces are like 100 percent abstract classes but not the classes.
"Interfaces are contracts for what a class can do"
A reason for introducing interface is, we can extend only single class but interface brought a new thing implement in java so we can implement thousands of interface.So we can not say that it is a class.
you can get more about this Here!
Interface is just a contract which all implementing classes should follow.
An interface is something like a template which cannot make an impact until a class implements it.
Yes, an interface is an instance of java.lang.Class. If you have a Class you can interrogate it to see if it is an interface: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInterface()
An interface(is a group of related methods with empty bodies.) is just an interface. Its not a class(A class is the blueprint from which individual objects are created).
notice that you define an interface like this
interface Bicycle {....}
and a class is defined like this
class MyBMX implements Bicycle{...}
So an Interface is an Interface and NOT a class
yes interface is a kind of class.simply say in class methods and data present also in interface method(only abstract method) and data(only static and final) present.
for more watch it
https://www.youtube.com/watch?v=qgBv1_Plldo&list=PLbRMhDVUMngcx5xHChJ-f7ofxZI4JzuQR&index=21&t=13:52
We can get class Class object by 3 methods:
MyClass.class
obj.getClass
Class.forName("className")
I don't understood the difference between: MyClass.class and Class.forName("className").
Because both will need Class Name.
Class.forName("className");
forName is a static method of class "Class".
we require to provide the fully qualified name of the desired class.
this can be used when name of class will come to known at runtime.
ClassName.class;
.class is not a method it is a keyword and can be used with primitive type like int.
when Name of Class is known in advance & it is added to project, that time we use ClassName.class
I don't understood the difference between: MyClass.class and Class.forName("className").
Because both will need Class Name.
The big difference is when they need it. Since Class.forName accepts a string, the class name can be determined at runtime. Whereas of course, MyClass.class is determined at compile-time. This makes Class.forName useful for dynamically loading classes based on configuration (for instance, loading database drivers depending on the settings of a config file).
Rounding things out: obj.getClass() is useful because you may not know the actual class of an object — for instance, in a method where you accept an argument using an interface, rather than class, such as in foo(Map m). You don't know the class of m, just that it's something that implements Map. (And 99% of the time, you shouldn't care what its class is, but that 1% crops up occasionally.)
Class.forName("className");
It dynamically load the class based on fully qualified class name string.
obj.getClass
Returns the java.lang.Class object that represents the runtime class of the object.
MyClass.class:
A class literal is an expression consisting of the name of a class, interface, array,
or primitive type, or the pseudo-type void, followed by a'.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type is Class<C>.
http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf
One important difference is:
A.class will perform loading and linking of class A.
Class.forName("A") will perform loading, linking and initialization of class A.
What is the java class type used for? I am confused about what it means and how it is different than declaring an object type:
Class className;
Thanks
There are several uses for a Class object. For example, say I want to create an instance of a class based on some class name stored in a config file.
String className = config.myClass;
Class clazz = Class.forName(className);
Object myClassInstance = clazz.newInstance();
It represents the runtime type of the object. The actual programmatic use of the Class type is often found in reflection and generics.
For example, loading a JDBC driver abstractly with help of Class#forName():
String jdbcDriverClassName = getItFromSomeExternalConfigurationFile();
Class.forName(jdbcDriverClassName);
Or typecasting an generic Object to a beforeknown type:
public static <T> T findAttribute(String key, Class<T> type) {
return type.cast(attributeMap.get(key)); // It's a Map<String, Object>.
}
...which can be used as
SomeType instance = findAttribute("someKey", SomeType.class);
A more extended example can be found here in flavor of a "generic object converter".
Actually, reading the java.lang.Class javadoc, including all of the available methods, should give you an idea what it can be used for.
Class is a special type of Object, i.e Class is a sub class of Object. Every class you define has its own Class object. You can access this as MyObject.class or myInstance.getClass(). In another word, any class you define has a Class attribute where as any class is an Object. I agree it is slightly confusing to a newbie.
javadoc says:
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
You can use it when checking the type of some variable or check for inheritance runtime.
It's also used in reflection, to load dynamically types and execute methods on them.
From the book Thinking in Java:
The Class object
To understand how Run Time Type Information (RTTI) works in Java, you must first know how type information is represented at run time. This is accomplished through a
special kind of object called the Class object, which contains information
about the class. In fact, the Class object is used to create all of the
'regular' objects of your class.