Instantiating object in Python same as Java using jython - java

In Java I was able to run my code as:
(This are just sample naming)
import com.projectname.api.APIOne;
import com.projectname.api.APITwo;
import com.projectname.api.APIThree;
import com.projectname.api.APIFour;
import com.projectname.api.MainAPI;
public class TestMain {
public static void main(String[] args) {
APIOne a = APIOne.getName();
APITwo b = APIThree.getAddress();
APIFour d = b.getEmail();
MainAPI mainapi = new MainAPI();
mainapi.setEmail(d)
}
}
It is running okay, I tried converting this to Python as:
import com.projectname.api.APIOne as APIOne;
import com.projectname.api.APITwo as APITwo;
import com.projectname.api.APIThree as APIThree;
import com.projectname.api.APIFour as APIFour;
def test():
a = APIOne.getName();
b = APIThree.getAddress();
d = b.getEmail();
mainapi = MainAPI();
mainapi.setEmail(d)
test()
But is this the right way of instantiating? It make me confuse on instantiating.
Hope you could help me.

Importing a class from a java package or python module is normally written as:
from java.lang import Math
Rather than:
import java.lang.Math as Math
But, your code is correct.

I don't understand why you are confused, but this is correct, you could check the Jython documentation about instantiating Java objects using Jython and instantiates the objects the same way as you do.

Related

instantiate object from derived class with constructor that takes super argument

Maybe what I am trying to do is not worthwhile, it sure feels that way after spending many days on it.
I have A Base Class shown here:
package jimmy.kilmer.com;
import java.awt.Color;
import jarPackageImports.AI;
import jarPackageImports.MovementAction;
import jarPackageImports.Info;
import jarPackageImports.PlayerAction;
public class GameAI extends AI {
public gameAI(Info info) {
super(info);
setJerseyNumber(32);
}
public Color getColor() {
return Color.RED;
}
public String getName() {
return "Usain Bolt";
}
public PlayerAction update() {
// TODO game movement actions
// all available methods not listed here...
info.getVelocity();
info.getX();
info.getY();
MovementAction steeringBehavior = null;
return steeringBehavior;
}
//basically used for testing setup
public int[][] populateAllPossibleNodes() {
int[][] allPossibleNodes = new int[screenWidth/20][screenHeight/20];
return allPossibleNodes;
}
}
I have been given a jar, that sets up the game environment. It uses reflection for the setup. I am not familiar with reflection, unfortunately, as I am more beginner level.
I have read a lot about TDD, and am convinced that can help me stay orderly, and code in a disciplined way. I have some say that TDD is not really useful for Game development, which the arguments may be true, in regard to making an "enjoyable game." But, from a purely coding standpoint, I remain steadfast in my believe that TDD is the way to go. But, that remains to be seen, since it is still theoretical. I would like to try it.
I have installed Junit 5, and have done many tutorials, but it's all pretty basic examples. My particular test case uses reflection, super classes, derived classes, dynamic data. My head is spinning.
My goal is just to get setup such that I can start doing some Test driven development.
Here is my Junit test class:
package jimmy.kilmer.com;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import jarPackageImports.Info;
class GameAITest {
private GameAITest AIObject;
private jarPackageImports.Info info;
#BeforeEach
void setUp() throws Exception {
AIObject = new GameAITest(info);
#AfterEach
void tearDown() throws Exception {
}
#Test
void testPopulateAllPossibleNodes() {
// 1. given/arrange
int[][] array1 = new int[80][65];
// 2. when/act
int[][] array2 = AIObject.populateAllPossibleNodes();
// 3. then/assert
assertArrayEquals(array1, array2);
}
}
That is my best stab so far, but it still get a compile error. Specifically:
java.lang.NullPointerException:Cannot invoke "jarPackageImports.Info.getScene()" because "this.info" is null
In summation:
maybe everything I am trying is rubbish?
Do I need to use dynamic junit testing? I would have to read up on that.
Do I need to mock (use Mockito?) to instantiate an object to test? I would need to read up on that as well.
Is it possible to instantiate an object from GameAI? Do I need to/how would I use relection to do that? class.getConstructors()? And, I would have to read up on that.
thanks in advance.

Unable to import a Scala object into the Java project

I created a Scala object:
package myapp.data
import java.io.File
import myapp.models.NodeViewModel
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver
object ForumSerializer {
def openFile(file : File) : NodeViewModel = {
// doing something
}
def saveToFile(model : NodeViewModel) : Unit = {
// doing something
}
}
Then I tried to import it in another Java file
import myapp.ForumSerializer;
The error I get is:
Import myapp.ForumSerializer cannot be resolved.
What am I doing wrong?
Import it as ForumSerializer$.
Scala adds a $, so the compiler doesn't get confused with the class, when you have both an object and a class of the same name. You can then access the singleton object using the generated MODULE$.

How to create/use/import a custom made Method on Java

Like the in-built Math class, there are a couple of methods that one can use without importing the Math class. e.g
int io = (int) Math.random();
and notice the import region: no MATH whatsoever
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
but seeing, Math set doesn't have everything i needed, i created mine in a new class, but i can't seem to figure out what to do so i can be able to use it.
Taking a hint from the Math.java file, I've made my class final and my methods static but no avail..
Here's an excerpt of my code
package customops.Sets;
/**
*
* #author Kbluue
*/
public final class SetOpz {
public SetOpz(){}
public static int setMax(int[] set){
int out = set[0];
for(int i=1; i<set.length; i++){
out = Math.max(out, set[i]);
}
return out;
}
how do i use just the import command without having to copy and paste the SetOpz class in the DTL package?
You don't need to import Math explicitly because it is included by default. To use your own code you will have to import it. If you're using IntelliJ or Eclipse or some other smart IDE it will offer to import it for you automatically. Otherwise add a import statement at the top:
import customops.Sets.SetOpz;
You can import your method wherever you want to use with the following import statement
import static customops.Sets.SetOpz.setMax;

Managing files in Java

I know C++ at a decent level and I am trying to learn java. This will be a silly question but I cannot figure out how to import a .java file into another. I am at Eclipse IDE and in my project I have two files:
FileReader.java
Entry.java
I want to import the Entry.java in the other file but no matter what I do I get an error. Can you help me? Thx in advance.
FileReader.java :
import java.io.*;
class FileReader {
public static void main(String[] args) throws Exception {
System.out.println("Hello, World");
Entry a(10,"a title","a description");
a.print();
}
}
Entry.java:
public class Entry{
int ID;
String title;
String description;
public Entry(int id, String t,String d){
ID=id;
title=t;
description=d;
}
public void print(){
System.out.println("ID:"+ID);
System.out.println("Title:"+title);
System.out.println("Description:"+description);
}
}
At this state I get an error that Entry cannot be resolved as a variable. So I believe that it is related to the import.
Firstly
Entry a(10,"a title","a description");
should be
Entry a = new Entry (10,"a title","a description");
If Entry is in the same package then you will not need to import it.
If Entry is in a different package, say com.example then you will need to do
Either
import com.example.Entry;
or
import com.example.*;
The second import will import all classes in the com.example package - usually not such a good thing.
You need new Entry
The new keyword creates the new object
Entry a = new Entry(10,"a title","a description")
a.print();
An Entry object is created with the a reference with the above instantiation.
For the import part of your question, if two files are in the same package, no import is needed. If you Entry class was in a different package than your FileReader class, then you would need to import mypackage.Entry
Try
Entry a = new Entry(/*args*/);
And if you need to import the class, then use the absolute name (package+class) and put it after import above the class declaration
import com.example.you.Entry;
In Eclipse you can do Ctrl+Shift+O to resolve all imports.

NuiGetSensorCount Java JNA

I am just learning how to use Java JNA, and I am trying to call a simple function from the Microsoft Kinect SDK. (NuiGetSensorCount) which just returns the number of connected kinects.
Here is my attempt:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
public class Driver {
public interface KinectLibrary extends Library {
KinectLibrary INSTANCE = (KinectLibrary)Native.loadLibrary(("Microsoft.Kinect"),KinectLibrary.class);
//_Check_return_ HRESULT NUIAPI NuiGetSensorCount( _In_ int * pCount );
NativeLong NuiGetSensorCount(Pointer pCount);
}
public static void main(String[] args) {
Pointer devCount = new Pointer(0);
KinectLibrary.INSTANCE.NuiGetSensorCount(devCount);
System.out.println("Devices:"+devCount.getInt(0));
}
}
But I get:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'NuiGetSensorCount': The specified procedure could not be found.
at com.sun.jna.Function.<init>(Function.java:208)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:536)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:513)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:499)
at com.sun.jna.Library$Handler.invoke(Library.java:199)
at $Proxy0.NuiGetSensorCount(Unknown Source)
at Driver.main(Driver.java:30)
Can anybody provide help of how to change my code so it finds the correct native function? And also provide some information/reference so that I could try to debug this myself (some way to see what function Java JNA is looking for, and compare it to what the .dll contains)
I figured out my problem. First, I used a program called dependency walker http://dependencywalker.com/ to view all the symbols in the DLL and I determined that the DLL I was using (Microsoft.Kinect.dll) did not actually contain the function I was trying to call. I found out that Kinect10.dll was the one I needed. After changing that, I had to make a small change to my pointer and it works perfectly!
Here is the fixed code.
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;
public class Driver{
public interface KinectLibrary extends StdCallLibrary {
KinectLibrary INSTANCE = (KinectLibrary)Native.loadLibrary(("Kinect10"),KinectLibrary.class);
//_Check_return_ HRESULT NUIAPI NuiGetSensorCount( _In_ int * pCount );
NativeLong NuiGetSensorCount(IntByReference pCount);
}
public static void main(String[] args) {
IntByReference a = new IntByReference();
KinectLibrary.INSTANCE.NuiGetSensorCount(a);
System.out.println("Devices:"+a.getValue());
}
}

Categories