在Java中动态加载类 [英] Dynamically loading a class in Java

查看:124
本文介绍了在Java中动态加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查找了语法并搜索了api,但我仍然对这个过程感到困惑。我也搜索了Stackoverflow。加载类并从动态创建对象的正确方法是什么?换句话说,我希望用户指定要创建的对象类型,然后创建该类型的对象。我不想要一个菜单​​,因为我希望他们能够在当前目录中选择任何类。

I looked up the syntax and searched the api but am still confused about the process. I also searched Stackoverflow. What is the proper way to load a class and create an object out of it dynamically? In otherwords I want the user to specify what type of object they want to create, and then create that type of object. I don't want a menu, because I want them to be able to choose any class within the current directory.

推荐答案

假设该类具有no-arg构造函数,最简单的方法将是 -

Assuming the class has no-arg constructor, the simplest way would be -

Object newObject = Class.forName(strFullyQualifiedClassName).newInstance();

参考 - java.lang.Class

这篇关于在Java中动态加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆