在Java类中加载jar

时间:2015-04-23 14:44:42

标签: java jar classloader

我有一个简单的java类,我想在main方法中加载一个jar文件。如何加载jar以使其可用

  public static void main(String args[]) throws SQLException, IOException{

    String connectionString = "connectionstring";
    File platformDB = new File(tempDir, "PlatformDB.eap");

    createNewTempDirectory();
    Mirror  m = new Mirror(connectionString, createEmptyEap(emptyEapName) ,platformDB.getAbsolutePath());
    m.run();
}

镜像课程

    static {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
        }
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException e) {
        }
}

在Mirror.run方法中,我尝试建立与数据库的连接

Mirror.run()方法

 public void run() {
    this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
    this.source.setReadOnly(true);
}

我的jar文件位于" C:\ sqljdbc_4.0 \ enu \ sqljdbc4.jar" 如何加载此jar以便成功建立连接

谢谢

2 个答案:

答案 0 :(得分:0)

您只需使用-classpath选项运行该类:

java -classpath C:\sqljdbc_4.0\enu\sqljdbc4.jar

答案 1 :(得分:0)

最简单的方法是将jar添加到加载主类的类路径中。例如,如果Mirror是具有main方法的类,您可以从控制台

中说出
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;

import javax.swing.*;


public class Player extends JPanel implements ActionListener{
Timer time = new Timer(5, this);
double x = 0; double velX = 2;
double y = 0; double velY = 2;

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    Ellipse2D circle = new Ellipse2D.Double(x,y,40,40);
    g2.fill(circle);
    time.start();
}

public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();
    if(key == KeyEvent.VK_A){
        System.out.println("VK_A"); // When i press 'A' don't print this
        velX = 1;
        x = 1;
        x += velX;
        x += 1;
        //velY = 0;
    }
}



public void actionPerformed(ActionEvent e){
    //x += velX;
    //y += velY;
    //x = x + velX;
    //y = y + velY;
    repaint();
  }
}

将其修改为

`java Mirror'