-1

I have class similar as given below

public class MyClass<K,V>{

 public MyClass(Properties prop){
  Map<K,V> myMap = new HashMap<K,V>();
 }

}

I need to invoke this class by passing String as K and V as MyAnotherClass , but the MyAnotherClass will be taken as an user input through file, how to create the MyAnotherClass from a given name from file, and pass the same to MyClass<String,MyAnotherClass> = new MyClass<String,MyAnotherClass>() . what is the best way to achieve the same.

Any help would be appreciated.

Thanks

deva
  • 49
  • 6
  • 1
    I'm *lost*. What you're doing here will already let you create an instance of `MyClass`. – Makoto Aug 18 '17 at 14:47
  • I don't understand the question, what is the problem and what are you stuck on? – f1sh Aug 18 '17 at 14:49
  • 1
    i think she is talking about create a class from a String resolving the name – ΦXocę 웃 Пepeúpa ツ Aug 18 '17 at 14:51
  • I want to create an instance similar to `MyClass = new MyClass()` , but the argument may be identified at the run time. Instead of `MyAnotherClass` it will be taken from String as mentioned by @ΦXocę웃Пepeúpaツ – deva Aug 18 '17 at 14:57
  • See this https://stackoverflow.com/questions/7342035/dynamic-generic-typing-in-java – Murat Karagöz Aug 18 '17 at 15:01
  • I have scenario ,where the class (full qualified path) will be passed as a string , Using that value , how i can create the `MyClass` instance – deva Aug 18 '17 at 15:10
  • If you have full qualified path you can just use reflection to create an instance of your customclass. Maybe you can just create a wrapper class that take the string and reate an instance of the class indicated by it – rakwaht Aug 18 '17 at 15:24

1 Answers1

0

Java erases the types on compilation, so you need to have the user pass in the type (by passing in the Class object of the type) at runtime.

import java.util.Properties;
import java.util.HashMap;
import java.util.Map;

public class MyClass<V extends Class<V>> {

    public MyClass(Properties prop, V type){
        Map<String,V> myMap = new HashMap<String,V>();
    }

}

will give you what you need. It will be called like

new MyClass(properties, Customer.class);
Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
  • Thanks , this approach fixed the issue. – deva Aug 18 '17 at 16:17
  • @deva Glad it helped. It was a problem I first encountered a long time ago (when Generics was just pre-release). So, I'm glad I could share the answer I found. – Edwin Buck Aug 18 '17 at 18:07