B4J Question [solved] Create Class Instance From Variable

Squiffy

Active Member
Licensed User
Longtime User
Is it possible for me to create an instance of a class dynamically at runtime?

I mean I have a class defined elsewhere as "dave", and :

B4X:
dim myvar as string = "dave"
dim classinstance as myvar

so classinstance is of type "dave"
Obviously that's a trivial example.
 

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
I can not test ir right now but if i remember correctly, java object has an initialize method that would allow you to create an object with a string. Or may be with the reflection library.
 
Upvote 0

Squiffy

Active Member
Licensed User
Longtime User
I tried this :

B4X:
Dim v As JavaObject
v.InitializeNewInstance("View",Null)

where View is a class, but it complains that it can't find View. I'm sure I'm roughly in the right ballpark but struggling with the implementation....
 
Upvote 0

Squiffy

Active Member
Licensed User
Longtime User
Step closer :

B4X:
Dim v As JavaObject
v.InitializeNewInstance("b4j.template.view",Null)

gets me over that step, but I can't seem to run any methods inside that class. For example, this fails (can't find the method) :

B4X:
v.RunMethod("setHtmlFile",Array as Object("/pages/test.html"))
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Is the b4j.template.view a class you created using class module?

If so try using all lowercase name of functions if you are using JavaObject.

Or just use
B4X:
Dim myInstanceClass As view  '<< view would be your class module
...
myInstanceClass.Initialize
...
 
Last edited:
Upvote 0

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
Like daestrum said, if view is a class of yours, you should see how the b4x compiler is transforming that sub.

Use an utility like jdgui for that.

I believe that it adds a " _ " and is all lowercase.
 
Upvote 0

Squiffy

Active Member
Licensed User
Longtime User
@Enrique Gonzalez R - interesting - without the underscore I get Method not found, with the underscore I get Method not matched. Not sure what the difference is. I've tried every combination of upper & lower case; all lowercase is the only thing that seems to even hint at working. I know I pasted the mixed case example but I am actually using lower. Will investigate jdgui...

@Daestrum - I don't necessarily know at design time which class I want to instantiate.

@Erel - that's pretty much what I'm doing as a work around.If that's the only way then that's fine.
 
Upvote 0

Squiffy

Active Member
Licensed User
Longtime User
Perfect.
Silly thing is I was already using this technique to call a method defined in a variable within the same class. I just never made the connection to call it externally.

Thanks to all.
 
Upvote 0
Top