-4

I have a class suppose Learning.java

Can I instantiate that class using its name "Learning.java" ? I went through reflection in JAVA, But I think that instantiates only the .class objects.

I wanted to call a method calculate() through an interface ILearning.java

Learning.java has constructor which takes arguments (int a,int b,int c,int d)

and the calculate method takes those argument and returns double.

John Humanyun
  • 915
  • 3
  • 10
  • 25
  • 1
    Possible duplicate of [Can I Instantiate a class using the class object? What about Constructors?](https://stackoverflow.com/questions/712371/can-i-instantiate-a-class-using-the-class-object-what-about-constructors) – Carlos López Marí Apr 25 '19 at 09:08
  • What is your code, what is the input, what is the *specific* output? – luk2302 Apr 25 '19 at 09:08
  • This SO question might help you: https://stackoverflow.com/questions/2092659/what-is-the-difference-between-class-forname-and-class-forname-newinstanc – Jens Apr 25 '19 at 09:08
  • `Learning.java` is not a class. It is a file with source code. In order to instantiate an object, you need to compile the code(.class file) and load it in JVM via classloader. – NeplatnyUdaj Apr 25 '19 at 09:08
  • You can check here: https://stackoverflow.com/questions/9886266/is-there-a-way-to-instantiate-a-class-by-name-in-java – Jack Sierkstra Apr 25 '19 at 09:09
  • Stop explaining code, **show code**. What classes are involved, where do you have a `String` containing a class name, and why do you have it, where does it come from, why do you not just use a proper instance in the first place, etc!? – luk2302 Apr 25 '19 at 09:50

2 Answers2

0

You cannot instantiate using "Learning.java" file using reflection. However, having Learning.class file in the classpath and using reflection API such as Class.forName() you can instantiate.

javapedia.net
  • 2,531
  • 4
  • 25
  • 50
0

I was able to achieve this using the package name along with the class as below

 Class<?> myClass= Class.forName("com.Learning");

I got the desired results.

John Humanyun
  • 915
  • 3
  • 10
  • 25