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.

2
  • 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 Commented Nov 8, 2019 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. Commented Nov 8, 2019 at 10:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks gonna check that out!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.