Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call "Class" class as parameter in java

Tags:

java

for example I have following method in class BugReportFactory:

public static void addFactoryImpl(Class impl) { }

I want to call this method from another class by following ways:

BugReportFactory.addFactoryImpl(new BugReportFactoryAndroid());

It says that following Argument is not applicable for Class class.

Can anyone tell my mistake?

ONE MORE QUESTION:

private static IBugReportFactory INSTANCE = null; 
public static void addFactoryImpl(Class impl) { 
INSTANCE = (IBugReportFactory)impl; 
} 

But it shows errors specifying that you cannot cast class to object?

like image 908
Yatish Bathla Avatar asked Dec 06 '22 02:12

Yatish Bathla


1 Answers

Try following, Object class has a getClass() method

BugReportFactory.addFactoryImpl(new BugReportFactoryAndroid().getClass());

Or

BugReportFactory.addFactoryImpl(BugReportFactoryAndroid.class);

Will do the job.

ONE MORE QUESTION:

private static IBugReportFactory INSTANCE = null; 
public static void addFactoryImpl(Class impl) { 
     INSTANCE = (IBugReportFactory)impl; 
}

But it shows errors specifying that you cannot cast

Class is different instance is different. Change your INSTANCE Variable type as Class.

private static Class INSTANCE = null;
public static void addFactoryImpl(Class impl) { 
     INSTANCE = impl; 
}

Class is blue print of an instance. You can't assign an instance to Class reference. Both are two different things.

like image 192
Abimaran Kugathasan Avatar answered Dec 08 '22 16:12

Abimaran Kugathasan