0

So what I am trying to do is

  1. Take user input (that is supposed to be a file name) and check if that file exists in my current work folder. ( I DONT NEED HELP HERE, this is under control)
  2. If the file exists, I want to create an instance of that file. (I wanna do this so I can use reflections and check if the file is a particular interface, and check the constructor.

So for testing my program, i created an instance of a existing file like this:

File tempFile = new File("/CURRENTFOLDER/" + file + ".java");
//with the user input tempFile = Test1.


    if(tempFile.exists()){

        Test1 test1 = new Test1();
        Class<?> test1_class = test1.getClass();

but what i really wanna do is something like this:

   File tempFile = new File("CURRENTFOLDER" + file + ".java");

    if(tempFile.exists()){

        //Test1 test1 = new Test1();
        //Class<?> test1_class = test1.getClass();

        tempFile instance_of_tempFile = new tempFile();
        Class<?> ? test_class = instance_of_tempFile.getClass();

I know you can't write tempFile instance_of_tempFile = new tempFile();, but just included that so you understand what I'm trying to do.

Maxime B.
  • 1,116
  • 8
  • 21
Jappe
  • 85
  • 1
  • 7
  • 1
    There's no such thing as "creating an instance of a file". You seem to be mixing the concept of a file (something which lives outside Java) and a Class (something which lives inside). Please rewrite the question to clarify what (2) really means – drekbour Nov 08 '19 at 10:16
  • 1
    You cannot create an instance of a class that only exists as source code in a .java file. It needs to be compiled to a .class file and be present in the classpath so you can use it using `Class.byName`. – f1sh Nov 08 '19 at 10:23

1 Answers1

1

Actually it's possible by using ClassLoader's

Basically you have to implement a Class Loader with a functionality that you need an then you will be able to instantiate a class by the file.

Here is a brief how-to

This example also can be useful

Yuriy Tsarkov
  • 2,461
  • 2
  • 14
  • 28