### Access a Java Class with Constructor

To access a Java Class, make use of JavaObjects (requires the JavaObject library).
Below are some examples, based on the Class File.
Reference: http://docs.oracle.com/javase/8/docs/api/java/io/File.html
Example running an API method for an instance using a constructor for a file
Constructor - Description
File(String pathname) - Creates a new File instance by converting the given pathname string into an abstract pathname.
Define in B4J
Dim Path as String = "myfile.txt"
' The JavaObject for the constructor
Dim joFile As JavaObject
' Create the file instance for the path (the constructor)
' Results in (File) myfile.txt
joFile.InitializeNewInstance("java.io.File", Array As Object(Path))
Example API method
' Get long filename
Log("getCanonicalPath: " & joFile.RunMethod("getCanonicalPath", Null))
Output:
getCanonicalPath: C:\Daten\b4j\opensource\rosandbox\ui\Objects\s.txt
' Check if file exist
Log("exists: " & joFile.RunMethod("exists", Null))
Output:
exists: true
' Check if directory
Log("isDirectory: " & joFile.RunMethod("isDirectory", Null))
Output:
isDirectory: false
' toPath
Log("toPath: " & joFile.RunMethod("toPath", Null))
Output:
toPath: myfile.txt
Example Rename file
' Rename a file
' The path can contain full and different path, which would be the same as moving a file
' Reference: http://docs.oracle.com/javase/8/docs/api/java/io/File.html
`Sub renameFile(source As String, target As String)
Dim joFileSource As JavaObject
Dim joFileTarget As JavaObject
' Create the file instances for the files (the constructor)
joFileSource.InitializeNewInstance("java.io.File", Array As Object(source))
joFileTarget.InitializeNewInstance("java.io.File", Array As Object(target))
' Rename file to
joFileSource.RunMethod("renameTo", Array As Object(joFileTarget))
End Sub`
Example running an API method for an instance using a constructor for an Integer
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html
' Converts a number to a binary string, like in java Integer.toBinaryString
' Parameter: number to convert
' Returns the number as a binary string with length 8
`Private Sub ToBinaryString8(number As Int) As String
Dim result As String = ""
Dim joI As JavaObject
' Build a static class instance which return an Integer
joI.InitializeStatic("java.lang.Integer")
' Run API method with the Integer as Parameter = Integer.toBinaryString(Int)
result = joI.RunMethod("toBinaryString", Array(number))
Dim n As Int = result.Length
For i = n To 7
result = "0" & result
Next
Return result
End Sub`

Changed: , Category: JavaObject, File: T6C208M1517.htm, ID: 1517