How to dynamically create new class implementing some interface and instantiate it? - java

Is it possible to compose new class at runtime in Java?
What are the means for that? Refection? Compiler API?
I can do
package tests;
public class TryReflection02 {
interface A {
}
public static void main(String[] args) {
Object o = new A() {};
System.out.println( o.toString() );
o = A.class.newInstance() // exception
}
}
Can I do the same having A.class value?

No, you can't. A is an interface, and only classes can be instantiated.
What you can do is to use a library/helper that uses some trickery to create a class that implements the interface and instantiates that. The JDK's Proxy class contains static methods to do just that. There are also tools that can do it which are custom-geared for test-related use cases: mockito, for instance.
These tools do exactly what you hint at in this question's title: rather than instantiating the interface, they generate a new class that implements the interface, and then instantiate that class.

Related

SQLiteDatabe object, what method query returns? [duplicate]

This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc

Clarification on collection's iterator [duplicate]

This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc

Where it is useful to have nested classes in an interface? [duplicate]

This question already has answers here:
Inner class within Interface
(13 answers)
Closed 7 years ago.
In which scenario can an interface have nested classes?
The following code is allowed and valid.
public interface Iface {
void show();
class ifaceClass {
int x;
public ifaceClass() {
System.out.println(x);
}
}
}
I am also struggling to make object of class ifaceClass.
EDIT :
I am able to make object like this
public class Test implements Iface {
public static void main(String[] args){
ifaceClass ifaceClassObj = new ifaceClass();
}
public void show() {
}
}
I noticed if Test has not implemented the Iface then I needed following import,
import com.jls.Iface.ifaceClass;
But it boiled down to same problem that why not use it as a just another class.
What the difference or value addition with this approach ?
You can create an instance of ifaceClass inside the class that implements Iface:
interface Iface {
void show();
class ifaceClass {
int x;
public ifaceClass() {
System.out.println(x);
}
}
}
public class Test implements Iface {
public static void main(String args[]) {
ifaceClass iface = new ifaceClass();
}
#Override
public void show() {
// ...
}
}
If the class doesn't implement the interface, just create an instance like this:
Iface.ifaceClass iface = new Iface.ifaceClass();
Why create a class inside an interface? Basically for the same reason you create a class inside another class, to group related classes together.
Where it is useful to have nested classes in an interface?
There is no such case which can only be fulfilled with inner class of interface. It is syntactically valid to have inner class in interface and for the class which implement interface can create instance of class and apart from that Interface.Class can also make that class accessible because it can not be private at all.
I noticed if Test has not implemented the Iface then I needed
following import import com.jls.Iface.ifaceClass;
Not necessarily, if your interface is accessible your inner class will automatically become accessible.Here you are trying to access class directly without even importing interface in that case following statement need above import statement.
ifaceClass ifaceClassObj = new ifaceClass();
But it boiled down to same problem that why not use it as a just
another class. What the difference or value addition with this
approach
Exactly, creating another class can also provide you the same facility and I have never seen any use case in my day to day programming which can only be fulfilled with inner class of interface.It does not provide anything else than accessibility through the interface.
I have used it once which I think quite a bad practice though. One day we need to implement one common method in different classes which are implementing interface say X and we wanted to add one extra method to be used by all this classes to add one kind of check on the Object which only check some parameter and return boolean even though that use case can be fulfilled in other way but to be specific that it is only intended for classes which are implementing this interface we have added class in interface so that we can provide that method to implementing classes.(NOTE : Nowadays default method can be used in this case instead of inner class)
Here, it is wise to note that in huge projects it is quite impossible for anyone ( other than creator ) to note that any interface has inner class. So, until we implement that class or manually check the interface we can not came to know that interface has inner class.

Java: Interface reference?

We all know that you can't instantiate an interface in Java (directly at least).
But with something like this:
public class Test{
public interface Link {
void mySamplemethod();
String myString ="HELLO!";
}
public static void main(String []args){
Link b;
}
}
What exactly is b... and how could it ever have a practical purpose?
b is a variable of type Link that has no value, not even null. In order to have a practical purpose you must initialize it with an object reference whose class implements Link interface.
If you want to initialize Link with a non-null value, you should create a class that implements this interface. That's mandatory in Java. If you don't want to create a new class outside this class, you can create a new class inside the class or inside the method (which would be an anonymous class). Here's a sample:
public static void main(String []args){
Link b = new Link() {
#Override
public void mySampleMethod() {
System.out.println("hello");
}
};
b.mySampleMethod();
}
The purposes of using interfaces for programming instead of direct classes is already explained very well here: What does it mean to "program to an interface"? (no need to reinvent the wheel).
You can create a reference to an interface - you just cannot instantiate it. Let's say for example you have a interface A
public interface A {
public void someMethod();
}
Now you have another class that implements this interface
public class B implements A {
public void someMethod() { // do something }
public void someOtherMethod() { // do something else }
}
Now you can have something like
A a = new B();
While a reference type A it actually implements the method as defined in B. The object type is B. The reference type A indicates that it has only access to those methods in B that are specified by A and nothing else (in this case, it has access to someMethod() and not someOtherMethod()).
What exactly is b...
b contains a reference to an instance of a class that implements Link. The reference can, of course, be null.
and how could it ever have a practical purpose?
Its practical purpose is pretty much the same as any other Java reference.
Of course, the code as it is does not really put b to any use. However, it's not hard to imagine similar code that would (you'd need to have a class that implements Link, and create an instance of that class).
For instance interfaces are widely used in polymorphism. So if you have multiple classes implementing interface, you could keep them in the same way:
class One implements Link {..}
class Two implements Link {..}
public static void main(String[] arg) {
Vector<Link> links;
Link link1 = new One();
Link link2 = new Two();
links.add(link1);
links.add(link2);
for (Link l : links) {
l.mySampleMethod();
}
}

If I call an interface method, will it get the method body from implementation class and execute?

I have an interface Interface1. I have its implementation Imple implements Interface1 (all methods have been implemented :) ).
Now, consider a third class CheckCall, can I do a call in the class CheckCall like I mention below :
Interface1 interface1;
interface1.method();
All necessary imports have been done. Please tell me is it possible or not , if not then ok and if yes, then tell me what will happen if I've more than one implementing classes for the same interface and I'm doing the same call.
Well, you cannot call the method directly on the interface, but you can do what you wrote, more or less.
You wrote:
Interface1 interface1;
interface1.method();
This will work if you do this:
Interface1 interface1 = new CheckCall();
interface1.method();
then tell me what will happen if i
have more than one impl classes for
the same interface and i am doing the
same call
Well, that's the nice thing about Java: the problem you're referring to is called the "diamond problem":
http://en.wikipedia.org/wiki/Diamond_problem
And it doesn't really exist in Java because Java fully supports multiple inheritance, but only through "multiple (Java) interface inheritance" (* see comment).
So in your case when you call interface1.method() you're either calling Impl's method or CheckCall's method and there's no confusion possible.
Sure, your code works fine! You just have to initialize your variable interface1 with an actual implementation (i.e. new Imple()).
Check out this example, I used your class-names:
public class CheckCall {
interface Interface1 {
void method();
}
static class Imple implements Interface1 {
#Override
public void method() {
System.out.println("Imple.method1()");
}
}
public static void main(String[] args) {
Interface1 interface1;
interface1 = new Imple();
interface1.method();
}
}
Yes, but not as you have it written. You'd have to say:
Interface1 interface1 = new Imple();
You can create a variable of type Interface, and then instantiate it to the class that implements the interface. You see this quite often with the Java collections, for example:
List<String> a = new ArrayList<String>();
Actually, you should refer to methods by the interfaces that define them, but you need an actual implementing class. So I would usually do it like this:
// the variable is of type Interface1
Interface1 interface1 = new Imple();
// but the method will be executed on the Imple object
interface1.method();
No, you need to make the call on the object that implements the interface, not on the interface itself.
Edit: A variable with that type could be used but it would still need to be an class that implements that type. You can't create an instance of an interface.
No.
As you can't instanciate an interface, you'll have to create a Imple object, to use it as an Interface1 one like this :
Interface1 interface1 = new Imple();
interface1.method();
in fact, an interface main interest come from the ability to have a method return any object implementing it, without having to worry about given implementation. in your case, it could shows up as
public class CheckCall {
public Interface1 factoryMethod() {
return new Imple();
}
public void test() {
Interface1 used = factoryMethod();
used.method();
}
}

Categories