Get the interface name from the implementation class - java

Example :
List<String> list = new ArrayList<String>();
//This would give me the class name for the list reference variable.
list.getClass().getSimpleName();
I want to get the Interface name from the list reference variable.
Is there any way possible to do that?

Using Reflection you can invoke the Class.getInterfaces() method which returns an Array of Interfaces that your class implements.
list.getClass().getInterfaces()[0];
To get just the name
list.getClass().getInterfaces()[0].getSimpleName();

Class aClass = ... //obtain Class object.
Class[] interfaces = aClass.getInterfaces();

Related

return a class implementing an interface using reflections

I'm using reflections to find all classes implementing IAnimal Interface.
but how do I return a class instance using the animals set in the below code:
Reflections reflections = new Reflections(IAnimal.class);
Set<Class<? extends IAnimal>> animals= reflections.getSubTypesOf(IAnimal.class);
I have 3 classes implementing IAnimal interface Dog, Cat, Duck. and I want to apply this logic but I don't know how to do it.
method findAnimal(String animalName){
for (Iterator<Class<? extends Operations>> it = animals.iterator(); it.hasNext(); ) {
String classname=it.Name;
if (classname.eqauls(animalName)){
System.out.println("found");
return new class(); }
}}
I want the findAnimal method to return a class instance if matched with the passed string. i.e., if I passed a "Dog" string as a parameter, the method will return a dog class.
is it possible to do that, any ideas on how to implement the logic in the box above?
So this basically boils down to how to create an instance having the java.lang.Class that represents that type?
You can create an instance by using the following code:
Class<?> cl = it.next();
... if condition, you decide to create the instance of cl
IDog object= cl.getDeclaredConstructor().newInstance(); // will actuall be a Dog, Cat or whatever you've decided to create
Note, you've assumed that the default constructor exists (the constructor without arguments). This kind of assumption is necessary, because you have to know how to create the object of the class of your interest.
If you know, that you have constructor that takes some specific parameters (of specific types) you can pass the parameter types to the getDeclaredConstructor method. For example, for class Integer that has a constructor with one int argument the following will print "5":
Integer i = Integer.class.getDeclaredConstructor(int.class).newInstance(5);
System.out.println(i);

Create Object using the value of a Java variable

I need help I need to know if Java allows to create an object dynamically, using the value of a variable.
Example
// I have 2 classes:
public class Audit {
private Long idAudit
// constructors, get and set
}
publish class Example {
private Long idExample
// constructors, get and set
}
-------------------------------------------------- -----
// create Audit and Example class object
Audit objAudit = new Audit ();
Example objExample = new Example ();
my question is the following can you create an object either of type Audit or example using the value of a variable as I try to do in the following example. Example:
String className = "Audit"; // variable that contains the class of the Object to create
className auditObject = new ClassName (); // I use the variable classname to create the desired object
Clearly I get an error trying to create the object that way, my question is can I create an object dynamically or some other option to try to achieve what I need. Thank you
Reflection is what you are searching for
final String className = "Audit";
final Class<?> clazz = Class.forName(className);
final Object o = clazz.getConstructor().newInstance();
There are several ways you can do this.
One is called reflection, and I will let you read about it on your own.
The other one is called a factory pattern. You can create a class called ObjectFactory. in that class you will have a method public Object createObject(String type).
In the method you can check if the type you received is one of your known types, and based on the type you can create the instance of the correct class. It is better of your classes implement the same interface. Then of course your method would return the instance of that interface (or a common base class).

Is there a way to get all Memberclasses of a class and loop over them to excecute methods?

I have an ManagerCLass, which includes many other Objects. Here are methodes, that takes thes Objects and call an method on theses Objects..
Example:
public class Manager extends BaseManager {
ClassA classA = new ClassA();
ClassB classB = new ClassB();
ClassC classC = new ClassC();
ClassD classD = new ClassD();
ClassE classE = new ClassE();
public void callMethodsOnObjects() {
classA.printResult();
classB.printResult();
classC.printResult();
classD.printResult();
classE.printResult();
}
}
These classes have all the same Superclass. Now my Question is, is there a way to automate the callMethodsOnObjects()-method?
My Idea was to get all declaredClasses of the Managerclass. Then to Loop of the array an excecute the printResult()-methode on each Object.
Class<?>[] classes = Manager.class.getDeclaredClasses();
for (int i = 0; i < classes.length; i++) {
....
}
But this donĀ“t work. The Array is Empty.
So do you have an Idea if this a way to automate this?
There are still more methods that are structured this way.
I'm not getting anywhere here. Does it make sense to do it this way, as I imagined it?
OK, so the real problem here is that you are using Java terminology incorrectly.
There are no member classes of the Manager class. Yup. That's what I said!
A "member class" is a class that is declared inside another class. But there aren't any classes declared inside Manager.
However, there are fields ("member fields") declared inside Manager; i.e. classA, classB and so on. And these fields have classes; i.e. ClassA, ClassB and so on.
If you want to find the member fields of a class, use the Class.getDeclaredFields() method. This will give you an array of Field objects.
You can then get each field's class by calling Field.getType() on it. Then you can use reflection to lookup the classses printResult() method and invoke it on the value in the respective fields of a target object.
Notes:
The Class returned by getType() could denote a primitive type or array type rather than a class. This Class will represent the erased type of the field.
If you want the Type as it was declared in the source code, use Field.getGenericType() instead.

Assignment for a variable defined whose type is an interface

Any suitable real time example for this statement...?
If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.
interface defines a contract. Contract defines a set of rules. interface defines rules by declaring the methods (their signature : input parameter, return type , name, and also maybe sometimes some constraints as written in java docs for the implementation).
A reference variable declared of the type of some interface can only refer to the Objects of the class which adhers to the rules set in the contract as defined by that particular interface.
By reference variable we can invoke the methods on the object. Suppose the interface sets some method in its declaration and then we have a variable of type of that interface. Now those set methods should be able to be invoked by that variable. To do so it is mandatory that it only refers the object of the class implementing that particular interface.
By implementing an interface a concrete class ( non abstract) is bound to provide the implementation of the rules (methods) set by the Contract (interface).
List x = new ArrayList();// valid
List y = new LinkedList();// valid
List z = new StringBuffer(); // invalid as StringBuffer does not implements List interface.
public class StackOverflowQuestion {
private final List<Answer> answers = new ArrayList<>();
public void addAnswer(Answer answer) {
answers.add(answer);
}
}
Here the class ArrayList<T> implements the interface List<T>.

String to new object with parameters

How do i create a new instance of an object from a string?
I want to do this:
Event event = new Event("hello");
event.setName("nice!");
but only having
String object = "Event";
String object_variable_name = "event";
String object_params = "hello";
Is this possible?
You can instantiate a class with the reflection API. But you need the full class name, the simple name (= with no constructor) is not enough.
Class clazz = Class.forName("com.example.Event");
Constructor constructor = clazz.getConstructor(String.class);
Object instance = constructor.newInstance("hello");
Assigning it to a variable where the variables name and type are stored in Strings is not possible. The usual pattern to implement this is to use a map:
Map<String, Object> events = new HashMap<String, Object>();
events.put("event", event);
You can use java.lang.Class's getConstructor isnstead.
Here is how you get the class instance (so you can call the constructor): How to get a Class Object from the Class Name in Java
Now you can you the Beans API to get the getter for the property name. See this question: Java Reflection: Instantiate a new object with specified type
Or you can use reflectasm or reflections or commons-beanutils to make your life much more simple

Categories

Resources