简体   繁体   English

如何使用JPL在Java和Prolog之间共享对象状态?

[英]How to share an object state between java and prolog with JPL?

I want to create an object in java: 我想在Java中创建一个对象:

MyObject obj = new MyObject ();

and I want to pass it to prolog with a jpl query. 我想通过jpl查询将其传递给序言。

How can I accomplish java to prolog object passing? 我怎样才能完成Java到Prolog对象的传递?

I know that I could use jpl_new in a prolog file like this: 我知道我可以在这样的序言文件中使用jpl_new:

execMethod :-
  jpl_new('my_package.MyObject', [], Object),
  jpl_call(Object, myMethod, [], _ ).

But, I want to avoid the jpl_new call and just use the jpl_call with the java object obj. 但是,我想避免jpl_new调用,而只是将jpl_call与Java对象obj一起使用。

And converserly, How can I accomplish prolog to java object passing? 反过来说, 我该如何完成Java对象传递的序幕?

I mean passing to java, objects created with a jpl_new call. 我的意思是将通过jpl_new调用创建的对象传递给Java。

In other words, I want to share an object state between java and prolog. 换句话说,我想在java和prolog之间共享一个对象状态。

To access a Prolog knowledge base from within Java, you can use JPL Queries. 要从Java内部访问Prolog知识库,可以使用JPL查询。 Let's look at a simple, trivial example below: 让我们看下面一个简单的例子:

% Knowledge base (Prolog)
foo(x,bar).

all_foo(X,Y) :- foo(X,Y).

In java, we could then write: 在Java中,我们可以这样写:

String query = "all_foo(x,Y)";
System.out.println("First solution: " + Query.oneSolution(query).get("Y"));

which would return 'bar' as answer in Y. 它会在Y中返回“ bar”作为答案。

Vice versa -as you showed in your question- JPL can be used when we want to access Java functionality from within a Prolog file. 反之亦然-正如您在问题中所显示的-当我们想从Prolog文件中访问Java功能时,可以使用JPL。

Firstly, looking at the docs of jpl_call/4 , we see that its first arguments can be: 首先,查看jpl_call / 4的文档,我们看到它的第一个参数可以是:

  • a type, class object or classname (for static methods of the denoted class, or for static or instance methods of java.lang.Class) 类型,类对象或类名(用于表示的类的静态方法,或者用于java.lang.Class的静态或实例方法)
  • a class instance or array (for static or instance methods) 类实例或数组(用于静态或实例方法)

So you are free in how to pass your class information to jpl_call/4 to execute certain methods. 因此,您可以自由地将类信息传递给jpl_call / 4以执行某些方法。

Subsequently, you can access your Java model rather than executing logic by using jpl_get/3 . 随后,您可以使用jpl_get / 3来访问Java模型,而不是执行逻辑。 An example below is shown where we bind the Prolog variable Colour to a reference of a field of a Java car object held in the static final .colour field of the example.class.car class. 下面显示了一个示例,其中我们将Prolog变量Color绑定到example.class.car类的static final .colour字段中保存的Java car对象的字段的引用。

jpl_get('example.class.car', colour, Colour)

More generally: 更普遍:

jpl_get(+Class_or_Object, +Field, -Datum)

Hope this helped. 希望这会有所帮助。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM