Link to home
Start Free TrialLog in
Avatar of hellohowareu
hellohowareu

asked on

java.lang.InstantiationException.

hai,

can any one solve this for me

Class class = Class.forName("java.awt.Graphics");
Object obj = class.newInstance();

giving an error of java.lang.InstantiationException.
how to instantiate this type of abstract classess.


ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Why do you want to do this?
Avatar of kylar
kylar

You can't instantiate abstract objects using reflection. You need to instantiate a concrete subclass or else instantiate the abstract class and provide implementation for the unknown pieces..

eg:

AbstractTableModel model = new AbstractTableModel();//Won't Work.

AbstractTableModel model = new AbstractTableModel(){
public int getRowCount(){return 0;}
public int getColumnCount(){return 0;}
public Object getValueAt(int row, int col){return "";}
};//works...

Class myClass = Class.forName("javax.swing.table.AbstractTableModel");
Object obj = class.newInstance();//won't work.

Class myClass = Class.forName("javax.swing.table.DefaultTableModel");
Object obj = class.newInstance();//proper use. works.

Cheers,
Kylar
> You can't instantiate abstract objects using reflection

You can't instantiate abstract objects *ever*.
Braaaap. Brainfart. I guess I never considered that you're not really instantiating the Abstract class, you're instantiating an anonymous concrete subclass...
Damn you're good :)

Cheers,
Kylar
And what I also forgot to say.. was to answer your question hello... try this instead:

Class cl = Class.forName("java.awt.Graphics2D");
Object obj = cl.newInstance();

Good?

Cheers,
Kylar
Graphics2D is abstract as well :-)

The only way I know of to get a Graphics object is from a component, image or some object that has a graphics context associated with it.
Hello,

This question has been open for quite a while now and needs to be wrapped up.

Please do NOT accept this comment as an answer, as I am simply trying to alert those involved that the
question is still open.

If any of the experts could come back and post any suggestions as to how they feel this could be wrapped
up (delete, 0 PAQ, award points, etc), I'm sure the moderators would appreciate it.

Thank you,
What do you say objects? Split it? You told him it can't be done (and kept my muddled rambling straight)... I gave him a workaround..
Cheers,
Kylar
> I gave him a workaround..

But Graphics2D is also abstract :)

A split is fine :-)
LOL I meant that you need to create a concrete subclass. Man I don't know where my head has been lately.. too much writing engineering specs and not enough coding.

Cheers
Force accepted

** Mindphaser - Community Support Moderator **